all_test.go 100 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167
  1. // 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. package reflect_test
  5. import (
  6. "bytes"
  7. "encoding/base64"
  8. "flag"
  9. "fmt"
  10. "io"
  11. "math/rand"
  12. "os"
  13. . "reflect"
  14. "runtime"
  15. "sort"
  16. "strings"
  17. "sync"
  18. "testing"
  19. "time"
  20. "unsafe"
  21. )
  22. func TestBool(t *testing.T) {
  23. v := ValueOf(true)
  24. if v.Bool() != true {
  25. t.Fatal("ValueOf(true).Bool() = false")
  26. }
  27. }
  28. type integer int
  29. type T struct {
  30. a int
  31. b float64
  32. c string
  33. d *int
  34. }
  35. type pair struct {
  36. i interface{}
  37. s string
  38. }
  39. func isDigit(c uint8) bool { return '0' <= c && c <= '9' }
  40. func assert(t *testing.T, s, want string) {
  41. if s != want {
  42. t.Errorf("have %#q want %#q", s, want)
  43. }
  44. }
  45. func typestring(i interface{}) string { return TypeOf(i).String() }
  46. var typeTests = []pair{
  47. {struct{ x int }{}, "int"},
  48. {struct{ x int8 }{}, "int8"},
  49. {struct{ x int16 }{}, "int16"},
  50. {struct{ x int32 }{}, "int32"},
  51. {struct{ x int64 }{}, "int64"},
  52. {struct{ x uint }{}, "uint"},
  53. {struct{ x uint8 }{}, "uint8"},
  54. {struct{ x uint16 }{}, "uint16"},
  55. {struct{ x uint32 }{}, "uint32"},
  56. {struct{ x uint64 }{}, "uint64"},
  57. {struct{ x float32 }{}, "float32"},
  58. {struct{ x float64 }{}, "float64"},
  59. {struct{ x int8 }{}, "int8"},
  60. {struct{ x (**int8) }{}, "**int8"},
  61. {struct{ x (**integer) }{}, "**reflect_test.integer"},
  62. {struct{ x ([32]int32) }{}, "[32]int32"},
  63. {struct{ x ([]int8) }{}, "[]int8"},
  64. {struct{ x (map[string]int32) }{}, "map[string]int32"},
  65. {struct{ x (chan<- string) }{}, "chan<- string"},
  66. {struct {
  67. x struct {
  68. c chan *int32
  69. d float32
  70. }
  71. }{},
  72. "struct { c chan *int32; d float32 }",
  73. },
  74. {struct{ x (func(a int8, b int32)) }{}, "func(int8, int32)"},
  75. {struct {
  76. x struct {
  77. c func(chan *integer, *int8)
  78. }
  79. }{},
  80. "struct { c func(chan *reflect_test.integer, *int8) }",
  81. },
  82. {struct {
  83. x struct {
  84. a int8
  85. b int32
  86. }
  87. }{},
  88. "struct { a int8; b int32 }",
  89. },
  90. {struct {
  91. x struct {
  92. a int8
  93. b int8
  94. c int32
  95. }
  96. }{},
  97. "struct { a int8; b int8; c int32 }",
  98. },
  99. {struct {
  100. x struct {
  101. a int8
  102. b int8
  103. c int8
  104. d int32
  105. }
  106. }{},
  107. "struct { a int8; b int8; c int8; d int32 }",
  108. },
  109. {struct {
  110. x struct {
  111. a int8
  112. b int8
  113. c int8
  114. d int8
  115. e int32
  116. }
  117. }{},
  118. "struct { a int8; b int8; c int8; d int8; e int32 }",
  119. },
  120. {struct {
  121. x struct {
  122. a int8
  123. b int8
  124. c int8
  125. d int8
  126. e int8
  127. f int32
  128. }
  129. }{},
  130. "struct { a int8; b int8; c int8; d int8; e int8; f int32 }",
  131. },
  132. {struct {
  133. x struct {
  134. a int8 `reflect:"hi there"`
  135. }
  136. }{},
  137. `struct { a int8 "reflect:\"hi there\"" }`,
  138. },
  139. {struct {
  140. x struct {
  141. a int8 `reflect:"hi \x00there\t\n\"\\"`
  142. }
  143. }{},
  144. `struct { a int8 "reflect:\"hi \\x00there\\t\\n\\\"\\\\\"" }`,
  145. },
  146. {struct {
  147. x struct {
  148. f func(args ...int)
  149. }
  150. }{},
  151. "struct { f func(...int) }",
  152. },
  153. {struct {
  154. x (interface {
  155. a(func(func(int) int) func(func(int)) int)
  156. b()
  157. })
  158. }{},
  159. "interface { reflect_test.a(func(func(int) int) func(func(int)) int); reflect_test.b() }",
  160. },
  161. }
  162. var valueTests = []pair{
  163. {new(int), "132"},
  164. {new(int8), "8"},
  165. {new(int16), "16"},
  166. {new(int32), "32"},
  167. {new(int64), "64"},
  168. {new(uint), "132"},
  169. {new(uint8), "8"},
  170. {new(uint16), "16"},
  171. {new(uint32), "32"},
  172. {new(uint64), "64"},
  173. {new(float32), "256.25"},
  174. {new(float64), "512.125"},
  175. {new(complex64), "532.125+10i"},
  176. {new(complex128), "564.25+1i"},
  177. {new(string), "stringy cheese"},
  178. {new(bool), "true"},
  179. {new(*int8), "*int8(0)"},
  180. {new(**int8), "**int8(0)"},
  181. {new([5]int32), "[5]int32{0, 0, 0, 0, 0}"},
  182. {new(**integer), "**reflect_test.integer(0)"},
  183. {new(map[string]int32), "map[string]int32{<can't iterate on maps>}"},
  184. {new(chan<- string), "chan<- string"},
  185. {new(func(a int8, b int32)), "func(int8, int32)(0)"},
  186. {new(struct {
  187. c chan *int32
  188. d float32
  189. }),
  190. "struct { c chan *int32; d float32 }{chan *int32, 0}",
  191. },
  192. {new(struct{ c func(chan *integer, *int8) }),
  193. "struct { c func(chan *reflect_test.integer, *int8) }{func(chan *reflect_test.integer, *int8)(0)}",
  194. },
  195. {new(struct {
  196. a int8
  197. b int32
  198. }),
  199. "struct { a int8; b int32 }{0, 0}",
  200. },
  201. {new(struct {
  202. a int8
  203. b int8
  204. c int32
  205. }),
  206. "struct { a int8; b int8; c int32 }{0, 0, 0}",
  207. },
  208. }
  209. func testType(t *testing.T, i int, typ Type, want string) {
  210. s := typ.String()
  211. if s != want {
  212. t.Errorf("#%d: have %#q, want %#q", i, s, want)
  213. }
  214. }
  215. func TestTypes(t *testing.T) {
  216. for i, tt := range typeTests {
  217. testType(t, i, ValueOf(tt.i).Field(0).Type(), tt.s)
  218. }
  219. }
  220. func TestSet(t *testing.T) {
  221. for i, tt := range valueTests {
  222. v := ValueOf(tt.i)
  223. v = v.Elem()
  224. switch v.Kind() {
  225. case Int:
  226. v.SetInt(132)
  227. case Int8:
  228. v.SetInt(8)
  229. case Int16:
  230. v.SetInt(16)
  231. case Int32:
  232. v.SetInt(32)
  233. case Int64:
  234. v.SetInt(64)
  235. case Uint:
  236. v.SetUint(132)
  237. case Uint8:
  238. v.SetUint(8)
  239. case Uint16:
  240. v.SetUint(16)
  241. case Uint32:
  242. v.SetUint(32)
  243. case Uint64:
  244. v.SetUint(64)
  245. case Float32:
  246. v.SetFloat(256.25)
  247. case Float64:
  248. v.SetFloat(512.125)
  249. case Complex64:
  250. v.SetComplex(532.125 + 10i)
  251. case Complex128:
  252. v.SetComplex(564.25 + 1i)
  253. case String:
  254. v.SetString("stringy cheese")
  255. case Bool:
  256. v.SetBool(true)
  257. }
  258. s := valueToString(v)
  259. if s != tt.s {
  260. t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
  261. }
  262. }
  263. }
  264. func TestSetValue(t *testing.T) {
  265. for i, tt := range valueTests {
  266. v := ValueOf(tt.i).Elem()
  267. switch v.Kind() {
  268. case Int:
  269. v.Set(ValueOf(int(132)))
  270. case Int8:
  271. v.Set(ValueOf(int8(8)))
  272. case Int16:
  273. v.Set(ValueOf(int16(16)))
  274. case Int32:
  275. v.Set(ValueOf(int32(32)))
  276. case Int64:
  277. v.Set(ValueOf(int64(64)))
  278. case Uint:
  279. v.Set(ValueOf(uint(132)))
  280. case Uint8:
  281. v.Set(ValueOf(uint8(8)))
  282. case Uint16:
  283. v.Set(ValueOf(uint16(16)))
  284. case Uint32:
  285. v.Set(ValueOf(uint32(32)))
  286. case Uint64:
  287. v.Set(ValueOf(uint64(64)))
  288. case Float32:
  289. v.Set(ValueOf(float32(256.25)))
  290. case Float64:
  291. v.Set(ValueOf(512.125))
  292. case Complex64:
  293. v.Set(ValueOf(complex64(532.125 + 10i)))
  294. case Complex128:
  295. v.Set(ValueOf(complex128(564.25 + 1i)))
  296. case String:
  297. v.Set(ValueOf("stringy cheese"))
  298. case Bool:
  299. v.Set(ValueOf(true))
  300. }
  301. s := valueToString(v)
  302. if s != tt.s {
  303. t.Errorf("#%d: have %#q, want %#q", i, s, tt.s)
  304. }
  305. }
  306. }
  307. var _i = 7
  308. var valueToStringTests = []pair{
  309. {123, "123"},
  310. {123.5, "123.5"},
  311. {byte(123), "123"},
  312. {"abc", "abc"},
  313. {T{123, 456.75, "hello", &_i}, "reflect_test.T{123, 456.75, hello, *int(&7)}"},
  314. {new(chan *T), "*chan *reflect_test.T(&chan *reflect_test.T)"},
  315. {[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
  316. {&[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})"},
  317. {[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}"},
  318. {&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, "*[]int(&[]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})"},
  319. }
  320. func TestValueToString(t *testing.T) {
  321. for i, test := range valueToStringTests {
  322. s := valueToString(ValueOf(test.i))
  323. if s != test.s {
  324. t.Errorf("#%d: have %#q, want %#q", i, s, test.s)
  325. }
  326. }
  327. }
  328. func TestArrayElemSet(t *testing.T) {
  329. v := ValueOf(&[10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}).Elem()
  330. v.Index(4).SetInt(123)
  331. s := valueToString(v)
  332. const want = "[10]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
  333. if s != want {
  334. t.Errorf("[10]int: have %#q want %#q", s, want)
  335. }
  336. v = ValueOf([]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
  337. v.Index(4).SetInt(123)
  338. s = valueToString(v)
  339. const want1 = "[]int{1, 2, 3, 4, 123, 6, 7, 8, 9, 10}"
  340. if s != want1 {
  341. t.Errorf("[]int: have %#q want %#q", s, want1)
  342. }
  343. }
  344. func TestPtrPointTo(t *testing.T) {
  345. var ip *int32
  346. var i int32 = 1234
  347. vip := ValueOf(&ip)
  348. vi := ValueOf(&i).Elem()
  349. vip.Elem().Set(vi.Addr())
  350. if *ip != 1234 {
  351. t.Errorf("got %d, want 1234", *ip)
  352. }
  353. ip = nil
  354. vp := ValueOf(&ip).Elem()
  355. vp.Set(Zero(vp.Type()))
  356. if ip != nil {
  357. t.Errorf("got non-nil (%p), want nil", ip)
  358. }
  359. }
  360. func TestPtrSetNil(t *testing.T) {
  361. var i int32 = 1234
  362. ip := &i
  363. vip := ValueOf(&ip)
  364. vip.Elem().Set(Zero(vip.Elem().Type()))
  365. if ip != nil {
  366. t.Errorf("got non-nil (%d), want nil", *ip)
  367. }
  368. }
  369. func TestMapSetNil(t *testing.T) {
  370. m := make(map[string]int)
  371. vm := ValueOf(&m)
  372. vm.Elem().Set(Zero(vm.Elem().Type()))
  373. if m != nil {
  374. t.Errorf("got non-nil (%p), want nil", m)
  375. }
  376. }
  377. func TestAll(t *testing.T) {
  378. testType(t, 1, TypeOf((int8)(0)), "int8")
  379. testType(t, 2, TypeOf((*int8)(nil)).Elem(), "int8")
  380. typ := TypeOf((*struct {
  381. c chan *int32
  382. d float32
  383. })(nil))
  384. testType(t, 3, typ, "*struct { c chan *int32; d float32 }")
  385. etyp := typ.Elem()
  386. testType(t, 4, etyp, "struct { c chan *int32; d float32 }")
  387. styp := etyp
  388. f := styp.Field(0)
  389. testType(t, 5, f.Type, "chan *int32")
  390. f, present := styp.FieldByName("d")
  391. if !present {
  392. t.Errorf("FieldByName says present field is absent")
  393. }
  394. testType(t, 6, f.Type, "float32")
  395. f, present = styp.FieldByName("absent")
  396. if present {
  397. t.Errorf("FieldByName says absent field is present")
  398. }
  399. typ = TypeOf([32]int32{})
  400. testType(t, 7, typ, "[32]int32")
  401. testType(t, 8, typ.Elem(), "int32")
  402. typ = TypeOf((map[string]*int32)(nil))
  403. testType(t, 9, typ, "map[string]*int32")
  404. mtyp := typ
  405. testType(t, 10, mtyp.Key(), "string")
  406. testType(t, 11, mtyp.Elem(), "*int32")
  407. typ = TypeOf((chan<- string)(nil))
  408. testType(t, 12, typ, "chan<- string")
  409. testType(t, 13, typ.Elem(), "string")
  410. // make sure tag strings are not part of element type
  411. typ = TypeOf(struct {
  412. d []uint32 `reflect:"TAG"`
  413. }{}).Field(0).Type
  414. testType(t, 14, typ, "[]uint32")
  415. }
  416. func TestInterfaceGet(t *testing.T) {
  417. var inter struct {
  418. E interface{}
  419. }
  420. inter.E = 123.456
  421. v1 := ValueOf(&inter)
  422. v2 := v1.Elem().Field(0)
  423. assert(t, v2.Type().String(), "interface {}")
  424. i2 := v2.Interface()
  425. v3 := ValueOf(i2)
  426. assert(t, v3.Type().String(), "float64")
  427. }
  428. func TestInterfaceValue(t *testing.T) {
  429. var inter struct {
  430. E interface{}
  431. }
  432. inter.E = 123.456
  433. v1 := ValueOf(&inter)
  434. v2 := v1.Elem().Field(0)
  435. assert(t, v2.Type().String(), "interface {}")
  436. v3 := v2.Elem()
  437. assert(t, v3.Type().String(), "float64")
  438. i3 := v2.Interface()
  439. if _, ok := i3.(float64); !ok {
  440. t.Error("v2.Interface() did not return float64, got ", TypeOf(i3))
  441. }
  442. }
  443. func TestFunctionValue(t *testing.T) {
  444. var x interface{} = func() {}
  445. v := ValueOf(x)
  446. if fmt.Sprint(v.Interface()) != fmt.Sprint(x) {
  447. t.Fatalf("TestFunction returned wrong pointer")
  448. }
  449. assert(t, v.Type().String(), "func()")
  450. }
  451. var appendTests = []struct {
  452. orig, extra []int
  453. }{
  454. {make([]int, 2, 4), []int{22}},
  455. {make([]int, 2, 4), []int{22, 33, 44}},
  456. }
  457. func sameInts(x, y []int) bool {
  458. if len(x) != len(y) {
  459. return false
  460. }
  461. for i, xx := range x {
  462. if xx != y[i] {
  463. return false
  464. }
  465. }
  466. return true
  467. }
  468. func TestAppend(t *testing.T) {
  469. for i, test := range appendTests {
  470. origLen, extraLen := len(test.orig), len(test.extra)
  471. want := append(test.orig, test.extra...)
  472. // Convert extra from []int to []Value.
  473. e0 := make([]Value, len(test.extra))
  474. for j, e := range test.extra {
  475. e0[j] = ValueOf(e)
  476. }
  477. // Convert extra from []int to *SliceValue.
  478. e1 := ValueOf(test.extra)
  479. // Test Append.
  480. a0 := ValueOf(test.orig)
  481. have0 := Append(a0, e0...).Interface().([]int)
  482. if !sameInts(have0, want) {
  483. t.Errorf("Append #%d: have %v, want %v (%p %p)", i, have0, want, test.orig, have0)
  484. }
  485. // Check that the orig and extra slices were not modified.
  486. if len(test.orig) != origLen {
  487. t.Errorf("Append #%d origLen: have %v, want %v", i, len(test.orig), origLen)
  488. }
  489. if len(test.extra) != extraLen {
  490. t.Errorf("Append #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
  491. }
  492. // Test AppendSlice.
  493. a1 := ValueOf(test.orig)
  494. have1 := AppendSlice(a1, e1).Interface().([]int)
  495. if !sameInts(have1, want) {
  496. t.Errorf("AppendSlice #%d: have %v, want %v", i, have1, want)
  497. }
  498. // Check that the orig and extra slices were not modified.
  499. if len(test.orig) != origLen {
  500. t.Errorf("AppendSlice #%d origLen: have %v, want %v", i, len(test.orig), origLen)
  501. }
  502. if len(test.extra) != extraLen {
  503. t.Errorf("AppendSlice #%d extraLen: have %v, want %v", i, len(test.extra), extraLen)
  504. }
  505. }
  506. }
  507. func TestCopy(t *testing.T) {
  508. a := []int{1, 2, 3, 4, 10, 9, 8, 7}
  509. b := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
  510. c := []int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
  511. for i := 0; i < len(b); i++ {
  512. if b[i] != c[i] {
  513. t.Fatalf("b != c before test")
  514. }
  515. }
  516. a1 := a
  517. b1 := b
  518. aa := ValueOf(&a1).Elem()
  519. ab := ValueOf(&b1).Elem()
  520. for tocopy := 1; tocopy <= 7; tocopy++ {
  521. aa.SetLen(tocopy)
  522. Copy(ab, aa)
  523. aa.SetLen(8)
  524. for i := 0; i < tocopy; i++ {
  525. if a[i] != b[i] {
  526. t.Errorf("(i) tocopy=%d a[%d]=%d, b[%d]=%d",
  527. tocopy, i, a[i], i, b[i])
  528. }
  529. }
  530. for i := tocopy; i < len(b); i++ {
  531. if b[i] != c[i] {
  532. if i < len(a) {
  533. t.Errorf("(ii) tocopy=%d a[%d]=%d, b[%d]=%d, c[%d]=%d",
  534. tocopy, i, a[i], i, b[i], i, c[i])
  535. } else {
  536. t.Errorf("(iii) tocopy=%d b[%d]=%d, c[%d]=%d",
  537. tocopy, i, b[i], i, c[i])
  538. }
  539. } else {
  540. t.Logf("tocopy=%d elem %d is okay\n", tocopy, i)
  541. }
  542. }
  543. }
  544. }
  545. func TestCopyArray(t *testing.T) {
  546. a := [8]int{1, 2, 3, 4, 10, 9, 8, 7}
  547. b := [11]int{11, 22, 33, 44, 1010, 99, 88, 77, 66, 55, 44}
  548. c := b
  549. aa := ValueOf(&a).Elem()
  550. ab := ValueOf(&b).Elem()
  551. Copy(ab, aa)
  552. for i := 0; i < len(a); i++ {
  553. if a[i] != b[i] {
  554. t.Errorf("(i) a[%d]=%d, b[%d]=%d", i, a[i], i, b[i])
  555. }
  556. }
  557. for i := len(a); i < len(b); i++ {
  558. if b[i] != c[i] {
  559. t.Errorf("(ii) b[%d]=%d, c[%d]=%d", i, b[i], i, c[i])
  560. } else {
  561. t.Logf("elem %d is okay\n", i)
  562. }
  563. }
  564. }
  565. func TestBigUnnamedStruct(t *testing.T) {
  566. b := struct{ a, b, c, d int64 }{1, 2, 3, 4}
  567. v := ValueOf(b)
  568. b1 := v.Interface().(struct {
  569. a, b, c, d int64
  570. })
  571. if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d {
  572. t.Errorf("ValueOf(%v).Interface().(*Big) = %v", b, b1)
  573. }
  574. }
  575. type big struct {
  576. a, b, c, d, e int64
  577. }
  578. func TestBigStruct(t *testing.T) {
  579. b := big{1, 2, 3, 4, 5}
  580. v := ValueOf(b)
  581. b1 := v.Interface().(big)
  582. if b1.a != b.a || b1.b != b.b || b1.c != b.c || b1.d != b.d || b1.e != b.e {
  583. t.Errorf("ValueOf(%v).Interface().(big) = %v", b, b1)
  584. }
  585. }
  586. type Basic struct {
  587. x int
  588. y float32
  589. }
  590. type NotBasic Basic
  591. type DeepEqualTest struct {
  592. a, b interface{}
  593. eq bool
  594. }
  595. // Simple functions for DeepEqual tests.
  596. var (
  597. fn1 func() // nil.
  598. fn2 func() // nil.
  599. fn3 = func() { fn1() } // Not nil.
  600. )
  601. var deepEqualTests = []DeepEqualTest{
  602. // Equalities
  603. {nil, nil, true},
  604. {1, 1, true},
  605. {int32(1), int32(1), true},
  606. {0.5, 0.5, true},
  607. {float32(0.5), float32(0.5), true},
  608. {"hello", "hello", true},
  609. {make([]int, 10), make([]int, 10), true},
  610. {&[3]int{1, 2, 3}, &[3]int{1, 2, 3}, true},
  611. {Basic{1, 0.5}, Basic{1, 0.5}, true},
  612. {error(nil), error(nil), true},
  613. {map[int]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, true},
  614. {fn1, fn2, true},
  615. // Inequalities
  616. {1, 2, false},
  617. {int32(1), int32(2), false},
  618. {0.5, 0.6, false},
  619. {float32(0.5), float32(0.6), false},
  620. {"hello", "hey", false},
  621. {make([]int, 10), make([]int, 11), false},
  622. {&[3]int{1, 2, 3}, &[3]int{1, 2, 4}, false},
  623. {Basic{1, 0.5}, Basic{1, 0.6}, false},
  624. {Basic{1, 0}, Basic{2, 0}, false},
  625. {map[int]string{1: "one", 3: "two"}, map[int]string{2: "two", 1: "one"}, false},
  626. {map[int]string{1: "one", 2: "txo"}, map[int]string{2: "two", 1: "one"}, false},
  627. {map[int]string{1: "one"}, map[int]string{2: "two", 1: "one"}, false},
  628. {map[int]string{2: "two", 1: "one"}, map[int]string{1: "one"}, false},
  629. {nil, 1, false},
  630. {1, nil, false},
  631. {fn1, fn3, false},
  632. {fn3, fn3, false},
  633. {[][]int{{1}}, [][]int{{2}}, false},
  634. // Nil vs empty: not the same.
  635. {[]int{}, []int(nil), false},
  636. {[]int{}, []int{}, true},
  637. {[]int(nil), []int(nil), true},
  638. {map[int]int{}, map[int]int(nil), false},
  639. {map[int]int{}, map[int]int{}, true},
  640. {map[int]int(nil), map[int]int(nil), true},
  641. // Mismatched types
  642. {1, 1.0, false},
  643. {int32(1), int64(1), false},
  644. {0.5, "hello", false},
  645. {[]int{1, 2, 3}, [3]int{1, 2, 3}, false},
  646. {&[3]interface{}{1, 2, 4}, &[3]interface{}{1, 2, "s"}, false},
  647. {Basic{1, 0.5}, NotBasic{1, 0.5}, false},
  648. {map[uint]string{1: "one", 2: "two"}, map[int]string{2: "two", 1: "one"}, false},
  649. }
  650. func TestDeepEqual(t *testing.T) {
  651. for _, test := range deepEqualTests {
  652. if r := DeepEqual(test.a, test.b); r != test.eq {
  653. t.Errorf("DeepEqual(%v, %v) = %v, want %v", test.a, test.b, r, test.eq)
  654. }
  655. }
  656. }
  657. func TestTypeOf(t *testing.T) {
  658. // Special case for nil
  659. if typ := TypeOf(nil); typ != nil {
  660. t.Errorf("expected nil type for nil value; got %v", typ)
  661. }
  662. for _, test := range deepEqualTests {
  663. v := ValueOf(test.a)
  664. if !v.IsValid() {
  665. continue
  666. }
  667. typ := TypeOf(test.a)
  668. if typ != v.Type() {
  669. t.Errorf("TypeOf(%v) = %v, but ValueOf(%v).Type() = %v", test.a, typ, test.a, v.Type())
  670. }
  671. }
  672. }
  673. type Recursive struct {
  674. x int
  675. r *Recursive
  676. }
  677. func TestDeepEqualRecursiveStruct(t *testing.T) {
  678. a, b := new(Recursive), new(Recursive)
  679. *a = Recursive{12, a}
  680. *b = Recursive{12, b}
  681. if !DeepEqual(a, b) {
  682. t.Error("DeepEqual(recursive same) = false, want true")
  683. }
  684. }
  685. type _Complex struct {
  686. a int
  687. b [3]*_Complex
  688. c *string
  689. d map[float64]float64
  690. }
  691. func TestDeepEqualComplexStruct(t *testing.T) {
  692. m := make(map[float64]float64)
  693. stra, strb := "hello", "hello"
  694. a, b := new(_Complex), new(_Complex)
  695. *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
  696. *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
  697. if !DeepEqual(a, b) {
  698. t.Error("DeepEqual(complex same) = false, want true")
  699. }
  700. }
  701. func TestDeepEqualComplexStructInequality(t *testing.T) {
  702. m := make(map[float64]float64)
  703. stra, strb := "hello", "helloo" // Difference is here
  704. a, b := new(_Complex), new(_Complex)
  705. *a = _Complex{5, [3]*_Complex{a, b, a}, &stra, m}
  706. *b = _Complex{5, [3]*_Complex{b, a, a}, &strb, m}
  707. if DeepEqual(a, b) {
  708. t.Error("DeepEqual(complex different) = true, want false")
  709. }
  710. }
  711. type UnexpT struct {
  712. m map[int]int
  713. }
  714. func TestDeepEqualUnexportedMap(t *testing.T) {
  715. // Check that DeepEqual can look at unexported fields.
  716. x1 := UnexpT{map[int]int{1: 2}}
  717. x2 := UnexpT{map[int]int{1: 2}}
  718. if !DeepEqual(&x1, &x2) {
  719. t.Error("DeepEqual(x1, x2) = false, want true")
  720. }
  721. y1 := UnexpT{map[int]int{2: 3}}
  722. if DeepEqual(&x1, &y1) {
  723. t.Error("DeepEqual(x1, y1) = true, want false")
  724. }
  725. }
  726. func check2ndField(x interface{}, offs uintptr, t *testing.T) {
  727. s := ValueOf(x)
  728. f := s.Type().Field(1)
  729. if f.Offset != offs {
  730. t.Error("mismatched offsets in structure alignment:", f.Offset, offs)
  731. }
  732. }
  733. // Check that structure alignment & offsets viewed through reflect agree with those
  734. // from the compiler itself.
  735. func TestAlignment(t *testing.T) {
  736. type T1inner struct {
  737. a int
  738. }
  739. type T1 struct {
  740. T1inner
  741. f int
  742. }
  743. type T2inner struct {
  744. a, b int
  745. }
  746. type T2 struct {
  747. T2inner
  748. f int
  749. }
  750. x := T1{T1inner{2}, 17}
  751. check2ndField(x, uintptr(unsafe.Pointer(&x.f))-uintptr(unsafe.Pointer(&x)), t)
  752. x1 := T2{T2inner{2, 3}, 17}
  753. check2ndField(x1, uintptr(unsafe.Pointer(&x1.f))-uintptr(unsafe.Pointer(&x1)), t)
  754. }
  755. func Nil(a interface{}, t *testing.T) {
  756. n := ValueOf(a).Field(0)
  757. if !n.IsNil() {
  758. t.Errorf("%v should be nil", a)
  759. }
  760. }
  761. func NotNil(a interface{}, t *testing.T) {
  762. n := ValueOf(a).Field(0)
  763. if n.IsNil() {
  764. t.Errorf("value of type %v should not be nil", ValueOf(a).Type().String())
  765. }
  766. }
  767. func TestIsNil(t *testing.T) {
  768. // These implement IsNil.
  769. // Wrap in extra struct to hide interface type.
  770. doNil := []interface{}{
  771. struct{ x *int }{},
  772. struct{ x interface{} }{},
  773. struct{ x map[string]int }{},
  774. struct{ x func() bool }{},
  775. struct{ x chan int }{},
  776. struct{ x []string }{},
  777. }
  778. for _, ts := range doNil {
  779. ty := TypeOf(ts).Field(0).Type
  780. v := Zero(ty)
  781. v.IsNil() // panics if not okay to call
  782. }
  783. // Check the implementations
  784. var pi struct {
  785. x *int
  786. }
  787. Nil(pi, t)
  788. pi.x = new(int)
  789. NotNil(pi, t)
  790. var si struct {
  791. x []int
  792. }
  793. Nil(si, t)
  794. si.x = make([]int, 10)
  795. NotNil(si, t)
  796. var ci struct {
  797. x chan int
  798. }
  799. Nil(ci, t)
  800. ci.x = make(chan int)
  801. NotNil(ci, t)
  802. var mi struct {
  803. x map[int]int
  804. }
  805. Nil(mi, t)
  806. mi.x = make(map[int]int)
  807. NotNil(mi, t)
  808. var ii struct {
  809. x interface{}
  810. }
  811. Nil(ii, t)
  812. ii.x = 2
  813. NotNil(ii, t)
  814. var fi struct {
  815. x func(t *testing.T)
  816. }
  817. Nil(fi, t)
  818. fi.x = TestIsNil
  819. NotNil(fi, t)
  820. }
  821. func TestInterfaceExtraction(t *testing.T) {
  822. var s struct {
  823. W io.Writer
  824. }
  825. s.W = os.Stdout
  826. v := Indirect(ValueOf(&s)).Field(0).Interface()
  827. if v != s.W.(interface{}) {
  828. t.Error("Interface() on interface: ", v, s.W)
  829. }
  830. }
  831. func TestNilPtrValueSub(t *testing.T) {
  832. var pi *int
  833. if pv := ValueOf(pi); pv.Elem().IsValid() {
  834. t.Error("ValueOf((*int)(nil)).Elem().IsValid()")
  835. }
  836. }
  837. func TestMap(t *testing.T) {
  838. m := map[string]int{"a": 1, "b": 2}
  839. mv := ValueOf(m)
  840. if n := mv.Len(); n != len(m) {
  841. t.Errorf("Len = %d, want %d", n, len(m))
  842. }
  843. keys := mv.MapKeys()
  844. newmap := MakeMap(mv.Type())
  845. for k, v := range m {
  846. // Check that returned Keys match keys in range.
  847. // These aren't required to be in the same order.
  848. seen := false
  849. for _, kv := range keys {
  850. if kv.String() == k {
  851. seen = true
  852. break
  853. }
  854. }
  855. if !seen {
  856. t.Errorf("Missing key %q", k)
  857. }
  858. // Check that value lookup is correct.
  859. vv := mv.MapIndex(ValueOf(k))
  860. if vi := vv.Int(); vi != int64(v) {
  861. t.Errorf("Key %q: have value %d, want %d", k, vi, v)
  862. }
  863. // Copy into new map.
  864. newmap.SetMapIndex(ValueOf(k), ValueOf(v))
  865. }
  866. vv := mv.MapIndex(ValueOf("not-present"))
  867. if vv.IsValid() {
  868. t.Errorf("Invalid key: got non-nil value %s", valueToString(vv))
  869. }
  870. newm := newmap.Interface().(map[string]int)
  871. if len(newm) != len(m) {
  872. t.Errorf("length after copy: newm=%d, m=%d", len(newm), len(m))
  873. }
  874. for k, v := range newm {
  875. mv, ok := m[k]
  876. if mv != v {
  877. t.Errorf("newm[%q] = %d, but m[%q] = %d, %v", k, v, k, mv, ok)
  878. }
  879. }
  880. newmap.SetMapIndex(ValueOf("a"), Value{})
  881. v, ok := newm["a"]
  882. if ok {
  883. t.Errorf("newm[\"a\"] = %d after delete", v)
  884. }
  885. mv = ValueOf(&m).Elem()
  886. mv.Set(Zero(mv.Type()))
  887. if m != nil {
  888. t.Errorf("mv.Set(nil) failed")
  889. }
  890. }
  891. func TestNilMap(t *testing.T) {
  892. var m map[string]int
  893. mv := ValueOf(m)
  894. keys := mv.MapKeys()
  895. if len(keys) != 0 {
  896. t.Errorf(">0 keys for nil map: %v", keys)
  897. }
  898. // Check that value for missing key is zero.
  899. x := mv.MapIndex(ValueOf("hello"))
  900. if x.Kind() != Invalid {
  901. t.Errorf("m.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
  902. }
  903. // Check big value too.
  904. var mbig map[string][10 << 20]byte
  905. x = ValueOf(mbig).MapIndex(ValueOf("hello"))
  906. if x.Kind() != Invalid {
  907. t.Errorf("mbig.MapIndex(\"hello\") for nil map = %v, want Invalid Value", x)
  908. }
  909. // Test that deletes from a nil map succeed.
  910. mv.SetMapIndex(ValueOf("hi"), Value{})
  911. }
  912. func TestChan(t *testing.T) {
  913. for loop := 0; loop < 2; loop++ {
  914. var c chan int
  915. var cv Value
  916. // check both ways to allocate channels
  917. switch loop {
  918. case 1:
  919. c = make(chan int, 1)
  920. cv = ValueOf(c)
  921. case 0:
  922. cv = MakeChan(TypeOf(c), 1)
  923. c = cv.Interface().(chan int)
  924. }
  925. // Send
  926. cv.Send(ValueOf(2))
  927. if i := <-c; i != 2 {
  928. t.Errorf("reflect Send 2, native recv %d", i)
  929. }
  930. // Recv
  931. c <- 3
  932. if i, ok := cv.Recv(); i.Int() != 3 || !ok {
  933. t.Errorf("native send 3, reflect Recv %d, %t", i.Int(), ok)
  934. }
  935. // TryRecv fail
  936. val, ok := cv.TryRecv()
  937. if val.IsValid() || ok {
  938. t.Errorf("TryRecv on empty chan: %s, %t", valueToString(val), ok)
  939. }
  940. // TryRecv success
  941. c <- 4
  942. val, ok = cv.TryRecv()
  943. if !val.IsValid() {
  944. t.Errorf("TryRecv on ready chan got nil")
  945. } else if i := val.Int(); i != 4 || !ok {
  946. t.Errorf("native send 4, TryRecv %d, %t", i, ok)
  947. }
  948. // TrySend fail
  949. c <- 100
  950. ok = cv.TrySend(ValueOf(5))
  951. i := <-c
  952. if ok {
  953. t.Errorf("TrySend on full chan succeeded: value %d", i)
  954. }
  955. // TrySend success
  956. ok = cv.TrySend(ValueOf(6))
  957. if !ok {
  958. t.Errorf("TrySend on empty chan failed")
  959. } else {
  960. if i = <-c; i != 6 {
  961. t.Errorf("TrySend 6, recv %d", i)
  962. }
  963. }
  964. // Close
  965. c <- 123
  966. cv.Close()
  967. if i, ok := cv.Recv(); i.Int() != 123 || !ok {
  968. t.Errorf("send 123 then close; Recv %d, %t", i.Int(), ok)
  969. }
  970. if i, ok := cv.Recv(); i.Int() != 0 || ok {
  971. t.Errorf("after close Recv %d, %t", i.Int(), ok)
  972. }
  973. }
  974. // check creation of unbuffered channel
  975. var c chan int
  976. cv := MakeChan(TypeOf(c), 0)
  977. c = cv.Interface().(chan int)
  978. if cv.TrySend(ValueOf(7)) {
  979. t.Errorf("TrySend on sync chan succeeded")
  980. }
  981. if v, ok := cv.TryRecv(); v.IsValid() || ok {
  982. t.Errorf("TryRecv on sync chan succeeded: isvalid=%v ok=%v", v.IsValid(), ok)
  983. }
  984. // len/cap
  985. cv = MakeChan(TypeOf(c), 10)
  986. c = cv.Interface().(chan int)
  987. for i := 0; i < 3; i++ {
  988. c <- i
  989. }
  990. if l, m := cv.Len(), cv.Cap(); l != len(c) || m != cap(c) {
  991. t.Errorf("Len/Cap = %d/%d want %d/%d", l, m, len(c), cap(c))
  992. }
  993. }
  994. // caseInfo describes a single case in a select test.
  995. type caseInfo struct {
  996. desc string
  997. canSelect bool
  998. recv Value
  999. closed bool
  1000. helper func()
  1001. panic bool
  1002. }
  1003. var allselect = flag.Bool("allselect", false, "exhaustive select test")
  1004. func TestSelect(t *testing.T) {
  1005. selectWatch.once.Do(func() { go selectWatcher() })
  1006. var x exhaustive
  1007. nch := 0
  1008. newop := func(n int, cap int) (ch, val Value) {
  1009. nch++
  1010. if nch%101%2 == 1 {
  1011. c := make(chan int, cap)
  1012. ch = ValueOf(c)
  1013. val = ValueOf(n)
  1014. } else {
  1015. c := make(chan string, cap)
  1016. ch = ValueOf(c)
  1017. val = ValueOf(fmt.Sprint(n))
  1018. }
  1019. return
  1020. }
  1021. for n := 0; x.Next(); n++ {
  1022. if testing.Short() && n >= 1000 {
  1023. break
  1024. }
  1025. if n >= 100000 && !*allselect {
  1026. break
  1027. }
  1028. if n%100000 == 0 && testing.Verbose() {
  1029. println("TestSelect", n)
  1030. }
  1031. var cases []SelectCase
  1032. var info []caseInfo
  1033. // Ready send.
  1034. if x.Maybe() {
  1035. ch, val := newop(len(cases), 1)
  1036. cases = append(cases, SelectCase{
  1037. Dir: SelectSend,
  1038. Chan: ch,
  1039. Send: val,
  1040. })
  1041. info = append(info, caseInfo{desc: "ready send", canSelect: true})
  1042. }
  1043. // Ready recv.
  1044. if x.Maybe() {
  1045. ch, val := newop(len(cases), 1)
  1046. ch.Send(val)
  1047. cases = append(cases, SelectCase{
  1048. Dir: SelectRecv,
  1049. Chan: ch,
  1050. })
  1051. info = append(info, caseInfo{desc: "ready recv", canSelect: true, recv: val})
  1052. }
  1053. // Blocking send.
  1054. if x.Maybe() {
  1055. ch, val := newop(len(cases), 0)
  1056. cases = append(cases, SelectCase{
  1057. Dir: SelectSend,
  1058. Chan: ch,
  1059. Send: val,
  1060. })
  1061. // Let it execute?
  1062. if x.Maybe() {
  1063. f := func() { ch.Recv() }
  1064. info = append(info, caseInfo{desc: "blocking send", helper: f})
  1065. } else {
  1066. info = append(info, caseInfo{desc: "blocking send"})
  1067. }
  1068. }
  1069. // Blocking recv.
  1070. if x.Maybe() {
  1071. ch, val := newop(len(cases), 0)
  1072. cases = append(cases, SelectCase{
  1073. Dir: SelectRecv,
  1074. Chan: ch,
  1075. })
  1076. // Let it execute?
  1077. if x.Maybe() {
  1078. f := func() { ch.Send(val) }
  1079. info = append(info, caseInfo{desc: "blocking recv", recv: val, helper: f})
  1080. } else {
  1081. info = append(info, caseInfo{desc: "blocking recv"})
  1082. }
  1083. }
  1084. // Zero Chan send.
  1085. if x.Maybe() {
  1086. // Maybe include value to send.
  1087. var val Value
  1088. if x.Maybe() {
  1089. val = ValueOf(100)
  1090. }
  1091. cases = append(cases, SelectCase{
  1092. Dir: SelectSend,
  1093. Send: val,
  1094. })
  1095. info = append(info, caseInfo{desc: "zero Chan send"})
  1096. }
  1097. // Zero Chan receive.
  1098. if x.Maybe() {
  1099. cases = append(cases, SelectCase{
  1100. Dir: SelectRecv,
  1101. })
  1102. info = append(info, caseInfo{desc: "zero Chan recv"})
  1103. }
  1104. // nil Chan send.
  1105. if x.Maybe() {
  1106. cases = append(cases, SelectCase{
  1107. Dir: SelectSend,
  1108. Chan: ValueOf((chan int)(nil)),
  1109. Send: ValueOf(101),
  1110. })
  1111. info = append(info, caseInfo{desc: "nil Chan send"})
  1112. }
  1113. // nil Chan recv.
  1114. if x.Maybe() {
  1115. cases = append(cases, SelectCase{
  1116. Dir: SelectRecv,
  1117. Chan: ValueOf((chan int)(nil)),
  1118. })
  1119. info = append(info, caseInfo{desc: "nil Chan recv"})
  1120. }
  1121. // closed Chan send.
  1122. if x.Maybe() {
  1123. ch := make(chan int)
  1124. close(ch)
  1125. cases = append(cases, SelectCase{
  1126. Dir: SelectSend,
  1127. Chan: ValueOf(ch),
  1128. Send: ValueOf(101),
  1129. })
  1130. info = append(info, caseInfo{desc: "closed Chan send", canSelect: true, panic: true})
  1131. }
  1132. // closed Chan recv.
  1133. if x.Maybe() {
  1134. ch, val := newop(len(cases), 0)
  1135. ch.Close()
  1136. val = Zero(val.Type())
  1137. cases = append(cases, SelectCase{
  1138. Dir: SelectRecv,
  1139. Chan: ch,
  1140. })
  1141. info = append(info, caseInfo{desc: "closed Chan recv", canSelect: true, closed: true, recv: val})
  1142. }
  1143. var helper func() // goroutine to help the select complete
  1144. // Add default? Must be last case here, but will permute.
  1145. // Add the default if the select would otherwise
  1146. // block forever, and maybe add it anyway.
  1147. numCanSelect := 0
  1148. canProceed := false
  1149. canBlock := true
  1150. canPanic := false
  1151. helpers := []int{}
  1152. for i, c := range info {
  1153. if c.canSelect {
  1154. canProceed = true
  1155. canBlock = false
  1156. numCanSelect++
  1157. if c.panic {
  1158. canPanic = true
  1159. }
  1160. } else if c.helper != nil {
  1161. canProceed = true
  1162. helpers = append(helpers, i)
  1163. }
  1164. }
  1165. if !canProceed || x.Maybe() {
  1166. cases = append(cases, SelectCase{
  1167. Dir: SelectDefault,
  1168. })
  1169. info = append(info, caseInfo{desc: "default", canSelect: canBlock})
  1170. numCanSelect++
  1171. } else if canBlock {
  1172. // Select needs to communicate with another goroutine.
  1173. cas := &info[helpers[x.Choose(len(helpers))]]
  1174. helper = cas.helper
  1175. cas.canSelect = true
  1176. numCanSelect++
  1177. }
  1178. // Permute cases and case info.
  1179. // Doing too much here makes the exhaustive loop
  1180. // too exhausting, so just do two swaps.
  1181. for loop := 0; loop < 2; loop++ {
  1182. i := x.Choose(len(cases))
  1183. j := x.Choose(len(cases))
  1184. cases[i], cases[j] = cases[j], cases[i]
  1185. info[i], info[j] = info[j], info[i]
  1186. }
  1187. if helper != nil {
  1188. // We wait before kicking off a goroutine to satisfy a blocked select.
  1189. // The pause needs to be big enough to let the select block before
  1190. // we run the helper, but if we lose that race once in a while it's okay: the
  1191. // select will just proceed immediately. Not a big deal.
  1192. // For short tests we can grow [sic] the timeout a bit without fear of taking too long
  1193. pause := 10 * time.Microsecond
  1194. if testing.Short() {
  1195. pause = 100 * time.Microsecond
  1196. }
  1197. time.AfterFunc(pause, helper)
  1198. }
  1199. // Run select.
  1200. i, recv, recvOK, panicErr := runSelect(cases, info)
  1201. if panicErr != nil && !canPanic {
  1202. t.Fatalf("%s\npanicked unexpectedly: %v", fmtSelect(info), panicErr)
  1203. }
  1204. if panicErr == nil && canPanic && numCanSelect == 1 {
  1205. t.Fatalf("%s\nselected #%d incorrectly (should panic)", fmtSelect(info), i)
  1206. }
  1207. if panicErr != nil {
  1208. continue
  1209. }
  1210. cas := info[i]
  1211. if !cas.canSelect {
  1212. recvStr := ""
  1213. if recv.IsValid() {
  1214. recvStr = fmt.Sprintf(", received %v, %v", recv.Interface(), recvOK)
  1215. }
  1216. t.Fatalf("%s\nselected #%d incorrectly%s", fmtSelect(info), i, recvStr)
  1217. continue
  1218. }
  1219. if cas.panic {
  1220. t.Fatalf("%s\nselected #%d incorrectly (case should panic)", fmtSelect(info), i)
  1221. continue
  1222. }
  1223. if cases[i].Dir == SelectRecv {
  1224. if !recv.IsValid() {
  1225. t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, cas.recv.Interface(), !cas.closed)
  1226. }
  1227. if !cas.recv.IsValid() {
  1228. t.Fatalf("%s\nselected #%d but internal error: missing recv value", fmtSelect(info), i)
  1229. }
  1230. if recv.Interface() != cas.recv.Interface() || recvOK != !cas.closed {
  1231. if recv.Interface() == cas.recv.Interface() && recvOK == !cas.closed {
  1232. t.Fatalf("%s\nselected #%d, got %#v, %v, and DeepEqual is broken on %T", fmtSelect(info), i, recv.Interface(), recvOK, recv.Interface())
  1233. }
  1234. t.Fatalf("%s\nselected #%d but got %#v, %v, want %#v, %v", fmtSelect(info), i, recv.Interface(), recvOK, cas.recv.Interface(), !cas.closed)
  1235. }
  1236. } else {
  1237. if recv.IsValid() || recvOK {
  1238. t.Fatalf("%s\nselected #%d but got %v, %v, want %v, %v", fmtSelect(info), i, recv, recvOK, Value{}, false)
  1239. }
  1240. }
  1241. }
  1242. }
  1243. // selectWatch and the selectWatcher are a watchdog mechanism for running Select.
  1244. // If the selectWatcher notices that the select has been blocked for >1 second, it prints
  1245. // an error describing the select and panics the entire test binary.
  1246. var selectWatch struct {
  1247. sync.Mutex
  1248. once sync.Once
  1249. now time.Time
  1250. info []caseInfo
  1251. }
  1252. func selectWatcher() {
  1253. for {
  1254. time.Sleep(1 * time.Second)
  1255. selectWatch.Lock()
  1256. if selectWatch.info != nil && time.Since(selectWatch.now) > 1*time.Second {
  1257. fmt.Fprintf(os.Stderr, "TestSelect:\n%s blocked indefinitely\n", fmtSelect(selectWatch.info))
  1258. panic("select stuck")
  1259. }
  1260. selectWatch.Unlock()
  1261. }
  1262. }
  1263. // runSelect runs a single select test.
  1264. // It returns the values returned by Select but also returns
  1265. // a panic value if the Select panics.
  1266. func runSelect(cases []SelectCase, info []caseInfo) (chosen int, recv Value, recvOK bool, panicErr interface{}) {
  1267. defer func() {
  1268. panicErr = recover()
  1269. selectWatch.Lock()
  1270. selectWatch.info = nil
  1271. selectWatch.Unlock()
  1272. }()
  1273. selectWatch.Lock()
  1274. selectWatch.now = time.Now()
  1275. selectWatch.info = info
  1276. selectWatch.Unlock()
  1277. chosen, recv, recvOK = Select(cases)
  1278. return
  1279. }
  1280. // fmtSelect formats the information about a single select test.
  1281. func fmtSelect(info []caseInfo) string {
  1282. var buf bytes.Buffer
  1283. fmt.Fprintf(&buf, "\nselect {\n")
  1284. for i, cas := range info {
  1285. fmt.Fprintf(&buf, "%d: %s", i, cas.desc)
  1286. if cas.recv.IsValid() {
  1287. fmt.Fprintf(&buf, " val=%#v", cas.recv.Interface())
  1288. }
  1289. if cas.canSelect {
  1290. fmt.Fprintf(&buf, " canselect")
  1291. }
  1292. if cas.panic {
  1293. fmt.Fprintf(&buf, " panic")
  1294. }
  1295. fmt.Fprintf(&buf, "\n")
  1296. }
  1297. fmt.Fprintf(&buf, "}")
  1298. return buf.String()
  1299. }
  1300. type two [2]uintptr
  1301. // Difficult test for function call because of
  1302. // implicit padding between arguments.
  1303. func 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) {
  1304. return b, c, d, e, f, g, h
  1305. }
  1306. func TestFunc(t *testing.T) {
  1307. ret := ValueOf(dummy).Call([]Value{
  1308. ValueOf(byte(10)),
  1309. ValueOf(20),
  1310. ValueOf(byte(30)),
  1311. ValueOf(two{40, 50}),
  1312. ValueOf(byte(60)),
  1313. ValueOf(float32(70)),
  1314. ValueOf(byte(80)),
  1315. })
  1316. if len(ret) != 7 {
  1317. t.Fatalf("Call returned %d values, want 7", len(ret))
  1318. }
  1319. i := byte(ret[0].Uint())
  1320. j := int(ret[1].Int())
  1321. k := byte(ret[2].Uint())
  1322. l := ret[3].Interface().(two)
  1323. m := byte(ret[4].Uint())
  1324. n := float32(ret[5].Float())
  1325. o := byte(ret[6].Uint())
  1326. if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1327. 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)
  1328. }
  1329. }
  1330. type emptyStruct struct{}
  1331. type nonEmptyStruct struct {
  1332. member int
  1333. }
  1334. func returnEmpty() emptyStruct {
  1335. return emptyStruct{}
  1336. }
  1337. func takesEmpty(e emptyStruct) {
  1338. }
  1339. func returnNonEmpty(i int) nonEmptyStruct {
  1340. return nonEmptyStruct{member: i}
  1341. }
  1342. func takesNonEmpty(n nonEmptyStruct) int {
  1343. return n.member
  1344. }
  1345. func TestCallWithStruct(t *testing.T) {
  1346. r := ValueOf(returnEmpty).Call(nil)
  1347. if len(r) != 1 || r[0].Type() != TypeOf(emptyStruct{}) {
  1348. t.Errorf("returning empty struct returned %#v instead", r)
  1349. }
  1350. r = ValueOf(takesEmpty).Call([]Value{ValueOf(emptyStruct{})})
  1351. if len(r) != 0 {
  1352. t.Errorf("takesEmpty returned values: %#v", r)
  1353. }
  1354. r = ValueOf(returnNonEmpty).Call([]Value{ValueOf(42)})
  1355. if len(r) != 1 || r[0].Type() != TypeOf(nonEmptyStruct{}) || r[0].Field(0).Int() != 42 {
  1356. t.Errorf("returnNonEmpty returned %#v", r)
  1357. }
  1358. r = ValueOf(takesNonEmpty).Call([]Value{ValueOf(nonEmptyStruct{member: 42})})
  1359. if len(r) != 1 || r[0].Type() != TypeOf(1) || r[0].Int() != 42 {
  1360. t.Errorf("takesNonEmpty returned %#v", r)
  1361. }
  1362. }
  1363. func TestMakeFunc(t *testing.T) {
  1364. f := dummy
  1365. fv := MakeFunc(TypeOf(f), func(in []Value) []Value { return in })
  1366. ValueOf(&f).Elem().Set(fv)
  1367. // Call g with small arguments so that there is
  1368. // something predictable (and different from the
  1369. // correct results) in those positions on the stack.
  1370. g := dummy
  1371. g(1, 2, 3, two{4, 5}, 6, 7, 8)
  1372. // Call constructed function f.
  1373. i, j, k, l, m, n, o := f(10, 20, 30, two{40, 50}, 60, 70, 80)
  1374. if i != 10 || j != 20 || k != 30 || l != (two{40, 50}) || m != 60 || n != 70 || o != 80 {
  1375. 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)
  1376. }
  1377. }
  1378. func TestMakeFuncInterface(t *testing.T) {
  1379. fn := func(i int) int { return i }
  1380. incr := func(in []Value) []Value {
  1381. return []Value{ValueOf(int(in[0].Int() + 1))}
  1382. }
  1383. fv := MakeFunc(TypeOf(fn), incr)
  1384. ValueOf(&fn).Elem().Set(fv)
  1385. if r := fn(2); r != 3 {
  1386. t.Errorf("Call returned %d, want 3", r)
  1387. }
  1388. if r := fv.Call([]Value{ValueOf(14)})[0].Int(); r != 15 {
  1389. t.Errorf("Call returned %d, want 15", r)
  1390. }
  1391. if r := fv.Interface().(func(int) int)(26); r != 27 {
  1392. t.Errorf("Call returned %d, want 27", r)
  1393. }
  1394. }
  1395. func TestMakeFuncVariadic(t *testing.T) {
  1396. // Test that variadic arguments are packed into a slice and passed as last arg
  1397. fn := func(_ int, is ...int) []int { return nil }
  1398. fv := MakeFunc(TypeOf(fn), func(in []Value) []Value { return in[1:2] })
  1399. ValueOf(&fn).Elem().Set(fv)
  1400. r := fn(1, 2, 3)
  1401. if r[0] != 2 || r[1] != 3 {
  1402. t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1403. }
  1404. r = fn(1, []int{2, 3}...)
  1405. if r[0] != 2 || r[1] != 3 {
  1406. t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1407. }
  1408. r = fv.Call([]Value{ValueOf(1), ValueOf(2), ValueOf(3)})[0].Interface().([]int)
  1409. if r[0] != 2 || r[1] != 3 {
  1410. t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1411. }
  1412. r = fv.CallSlice([]Value{ValueOf(1), ValueOf([]int{2, 3})})[0].Interface().([]int)
  1413. if r[0] != 2 || r[1] != 3 {
  1414. t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1415. }
  1416. f := fv.Interface().(func(int, ...int) []int)
  1417. r = f(1, 2, 3)
  1418. if r[0] != 2 || r[1] != 3 {
  1419. t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1420. }
  1421. r = f(1, []int{2, 3}...)
  1422. if r[0] != 2 || r[1] != 3 {
  1423. t.Errorf("Call returned [%v, %v]; want 2, 3", r[0], r[1])
  1424. }
  1425. }
  1426. type Point struct {
  1427. x, y int
  1428. }
  1429. // This will be index 0.
  1430. func (p Point) AnotherMethod(scale int) int {
  1431. return -1
  1432. }
  1433. // This will be index 1.
  1434. func (p Point) Dist(scale int) int {
  1435. //println("Point.Dist", p.x, p.y, scale)
  1436. return p.x*p.x*scale + p.y*p.y*scale
  1437. }
  1438. // This will be index 2.
  1439. func (p Point) GCMethod(k int) int {
  1440. runtime.GC()
  1441. return k + p.x
  1442. }
  1443. // This will be index 3.
  1444. func (p Point) TotalDist(points ...Point) int {
  1445. tot := 0
  1446. for _, q := range points {
  1447. dx := q.x - p.x
  1448. dy := q.y - p.y
  1449. tot += dx*dx + dy*dy // Should call Sqrt, but it's just a test.
  1450. }
  1451. return tot
  1452. }
  1453. func TestMethod(t *testing.T) {
  1454. // Non-curried method of type.
  1455. p := Point{3, 4}
  1456. i := TypeOf(p).Method(1).Func.Call([]Value{ValueOf(p), ValueOf(10)})[0].Int()
  1457. if i != 250 {
  1458. t.Errorf("Type Method returned %d; want 250", i)
  1459. }
  1460. m, ok := TypeOf(p).MethodByName("Dist")
  1461. if !ok {
  1462. t.Fatalf("method by name failed")
  1463. }
  1464. i = m.Func.Call([]Value{ValueOf(p), ValueOf(11)})[0].Int()
  1465. if i != 275 {
  1466. t.Errorf("Type MethodByName returned %d; want 275", i)
  1467. }
  1468. i = TypeOf(&p).Method(1).Func.Call([]Value{ValueOf(&p), ValueOf(12)})[0].Int()
  1469. if i != 300 {
  1470. t.Errorf("Pointer Type Method returned %d; want 300", i)
  1471. }
  1472. m, ok = TypeOf(&p).MethodByName("Dist")
  1473. if !ok {
  1474. t.Fatalf("ptr method by name failed")
  1475. }
  1476. i = m.Func.Call([]Value{ValueOf(&p), ValueOf(13)})[0].Int()
  1477. if i != 325 {
  1478. t.Errorf("Pointer Type MethodByName returned %d; want 325", i)
  1479. }
  1480. // Curried method of value.
  1481. tfunc := TypeOf((func(int) int)(nil))
  1482. v := ValueOf(p).Method(1)
  1483. if tt := v.Type(); tt != tfunc {
  1484. t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1485. }
  1486. i = v.Call([]Value{ValueOf(14)})[0].Int()
  1487. if i != 350 {
  1488. t.Errorf("Value Method returned %d; want 350", i)
  1489. }
  1490. v = ValueOf(p).MethodByName("Dist")
  1491. if tt := v.Type(); tt != tfunc {
  1492. t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1493. }
  1494. i = v.Call([]Value{ValueOf(15)})[0].Int()
  1495. if i != 375 {
  1496. t.Errorf("Value MethodByName returned %d; want 375", i)
  1497. }
  1498. // Curried method of pointer.
  1499. v = ValueOf(&p).Method(1)
  1500. if tt := v.Type(); tt != tfunc {
  1501. t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1502. }
  1503. i = v.Call([]Value{ValueOf(16)})[0].Int()
  1504. if i != 400 {
  1505. t.Errorf("Pointer Value Method returned %d; want 400", i)
  1506. }
  1507. v = ValueOf(&p).MethodByName("Dist")
  1508. if tt := v.Type(); tt != tfunc {
  1509. t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1510. }
  1511. i = v.Call([]Value{ValueOf(17)})[0].Int()
  1512. if i != 425 {
  1513. t.Errorf("Pointer Value MethodByName returned %d; want 425", i)
  1514. }
  1515. // Curried method of interface value.
  1516. // Have to wrap interface value in a struct to get at it.
  1517. // Passing it to ValueOf directly would
  1518. // access the underlying Point, not the interface.
  1519. var x interface {
  1520. Dist(int) int
  1521. } = p
  1522. pv := ValueOf(&x).Elem()
  1523. v = pv.Method(0)
  1524. if tt := v.Type(); tt != tfunc {
  1525. t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1526. }
  1527. i = v.Call([]Value{ValueOf(18)})[0].Int()
  1528. if i != 450 {
  1529. t.Errorf("Interface Method returned %d; want 450", i)
  1530. }
  1531. v = pv.MethodByName("Dist")
  1532. if tt := v.Type(); tt != tfunc {
  1533. t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1534. }
  1535. i = v.Call([]Value{ValueOf(19)})[0].Int()
  1536. if i != 475 {
  1537. t.Errorf("Interface MethodByName returned %d; want 475", i)
  1538. }
  1539. }
  1540. func TestMethodValue(t *testing.T) {
  1541. p := Point{3, 4}
  1542. var i int64
  1543. // Curried method of value.
  1544. tfunc := TypeOf((func(int) int)(nil))
  1545. v := ValueOf(p).Method(1)
  1546. if tt := v.Type(); tt != tfunc {
  1547. t.Errorf("Value Method Type is %s; want %s", tt, tfunc)
  1548. }
  1549. i = ValueOf(v.Interface()).Call([]Value{ValueOf(10)})[0].Int()
  1550. if i != 250 {
  1551. t.Errorf("Value Method returned %d; want 250", i)
  1552. }
  1553. v = ValueOf(p).MethodByName("Dist")
  1554. if tt := v.Type(); tt != tfunc {
  1555. t.Errorf("Value MethodByName Type is %s; want %s", tt, tfunc)
  1556. }
  1557. i = ValueOf(v.Interface()).Call([]Value{ValueOf(11)})[0].Int()
  1558. if i != 275 {
  1559. t.Errorf("Value MethodByName returned %d; want 275", i)
  1560. }
  1561. // Curried method of pointer.
  1562. v = ValueOf(&p).Method(1)
  1563. if tt := v.Type(); tt != tfunc {
  1564. t.Errorf("Pointer Value Method Type is %s; want %s", tt, tfunc)
  1565. }
  1566. i = ValueOf(v.Interface()).Call([]Value{ValueOf(12)})[0].Int()
  1567. if i != 300 {
  1568. t.Errorf("Pointer Value Method returned %d; want 300", i)
  1569. }
  1570. v = ValueOf(&p).MethodByName("Dist")
  1571. if tt := v.Type(); tt != tfunc {
  1572. t.Errorf("Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1573. }
  1574. i = ValueOf(v.Interface()).Call([]Value{ValueOf(13)})[0].Int()
  1575. if i != 325 {
  1576. t.Errorf("Pointer Value MethodByName returned %d; want 325", i)
  1577. }
  1578. // Curried method of pointer to pointer.
  1579. pp := &p
  1580. v = ValueOf(&pp).Elem().Method(1)
  1581. if tt := v.Type(); tt != tfunc {
  1582. t.Errorf("Pointer Pointer Value Method Type is %s; want %s", tt, tfunc)
  1583. }
  1584. i = ValueOf(v.Interface()).Call([]Value{ValueOf(14)})[0].Int()
  1585. if i != 350 {
  1586. t.Errorf("Pointer Pointer Value Method returned %d; want 350", i)
  1587. }
  1588. v = ValueOf(&pp).Elem().MethodByName("Dist")
  1589. if tt := v.Type(); tt != tfunc {
  1590. t.Errorf("Pointer Pointer Value MethodByName Type is %s; want %s", tt, tfunc)
  1591. }
  1592. i = ValueOf(v.Interface()).Call([]Value{ValueOf(15)})[0].Int()
  1593. if i != 375 {
  1594. t.Errorf("Pointer Pointer Value MethodByName returned %d; want 375", i)
  1595. }
  1596. // Curried method of interface value.
  1597. // Have to wrap interface value in a struct to get at it.
  1598. // Passing it to ValueOf directly would
  1599. // access the underlying Point, not the interface.
  1600. var s = struct {
  1601. X interface {
  1602. Dist(int) int
  1603. }
  1604. }{p}
  1605. pv := ValueOf(s).Field(0)
  1606. v = pv.Method(0)
  1607. if tt := v.Type(); tt != tfunc {
  1608. t.Errorf("Interface Method Type is %s; want %s", tt, tfunc)
  1609. }
  1610. i = ValueOf(v.Interface()).Call([]Value{ValueOf(16)})[0].Int()
  1611. if i != 400 {
  1612. t.Errorf("Interface Method returned %d; want 400", i)
  1613. }
  1614. v = pv.MethodByName("Dist")
  1615. if tt := v.Type(); tt != tfunc {
  1616. t.Errorf("Interface MethodByName Type is %s; want %s", tt, tfunc)
  1617. }
  1618. i = ValueOf(v.Interface()).Call([]Value{ValueOf(17)})[0].Int()
  1619. if i != 425 {
  1620. t.Errorf("Interface MethodByName returned %d; want 425", i)
  1621. }
  1622. }
  1623. func TestVariadicMethodValue(t *testing.T) {
  1624. p := Point{3, 4}
  1625. points := []Point{{20, 21}, {22, 23}, {24, 25}}
  1626. want := int64(p.TotalDist(points[0], points[1], points[2]))
  1627. // Curried method of value.
  1628. tfunc := TypeOf((func(...Point) int)(nil))
  1629. v := ValueOf(p).Method(3)
  1630. if tt := v.Type(); tt != tfunc {
  1631. t.Errorf("Variadic Method Type is %s; want %s", tt, tfunc)
  1632. }
  1633. i := ValueOf(v.Interface()).Call([]Value{ValueOf(points[0]), ValueOf(points[1]), ValueOf(points[2])})[0].Int()
  1634. if i != want {
  1635. t.Errorf("Variadic Method returned %d; want %d", i, want)
  1636. }
  1637. i = ValueOf(v.Interface()).CallSlice([]Value{ValueOf(points)})[0].Int()
  1638. if i != want {
  1639. t.Errorf("Variadic Method CallSlice returned %d; want %d", i, want)
  1640. }
  1641. f := v.Interface().(func(...Point) int)
  1642. i = int64(f(points[0], points[1], points[2]))
  1643. if i != want {
  1644. t.Errorf("Variadic Method Interface returned %d; want %d", i, want)
  1645. }
  1646. i = int64(f(points...))
  1647. if i != want {
  1648. t.Errorf("Variadic Method Interface Slice returned %d; want %d", i, want)
  1649. }
  1650. }
  1651. // Reflect version of $GOROOT/test/method5.go
  1652. // Concrete types implementing M method.
  1653. // Smaller than a word, word-sized, larger than a word.
  1654. // Value and pointer receivers.
  1655. type Tinter interface {
  1656. M(int, byte) (byte, int)
  1657. }
  1658. type Tsmallv byte
  1659. func (v Tsmallv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  1660. type Tsmallp byte
  1661. func (p *Tsmallp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  1662. type Twordv uintptr
  1663. func (v Twordv) M(x int, b byte) (byte, int) { return b, x + int(v) }
  1664. type Twordp uintptr
  1665. func (p *Twordp) M(x int, b byte) (byte, int) { return b, x + int(*p) }
  1666. type Tbigv [2]uintptr
  1667. func (v Tbigv) M(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  1668. type Tbigp [2]uintptr
  1669. func (p *Tbigp) M(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  1670. // Again, with an unexported method.
  1671. type tsmallv byte
  1672. func (v tsmallv) m(x int, b byte) (byte, int) { return b, x + int(v) }
  1673. type tsmallp byte
  1674. func (p *tsmallp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
  1675. type twordv uintptr
  1676. func (v twordv) m(x int, b byte) (byte, int) { return b, x + int(v) }
  1677. type twordp uintptr
  1678. func (p *twordp) m(x int, b byte) (byte, int) { return b, x + int(*p) }
  1679. type tbigv [2]uintptr
  1680. func (v tbigv) m(x int, b byte) (byte, int) { return b, x + int(v[0]) + int(v[1]) }
  1681. type tbigp [2]uintptr
  1682. func (p *tbigp) m(x int, b byte) (byte, int) { return b, x + int(p[0]) + int(p[1]) }
  1683. type tinter interface {
  1684. m(int, byte) (byte, int)
  1685. }
  1686. // Embedding via pointer.
  1687. type Tm1 struct {
  1688. Tm2
  1689. }
  1690. type Tm2 struct {
  1691. *Tm3
  1692. }
  1693. type Tm3 struct {
  1694. *Tm4
  1695. }
  1696. type Tm4 struct {
  1697. }
  1698. func (t4 Tm4) M(x int, b byte) (byte, int) { return b, x + 40 }
  1699. func TestMethod5(t *testing.T) {
  1700. CheckF := func(name string, f func(int, byte) (byte, int), inc int) {
  1701. b, x := f(1000, 99)
  1702. if b != 99 || x != 1000+inc {
  1703. t.Errorf("%s(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  1704. }
  1705. }
  1706. CheckV := func(name string, i Value, inc int) {
  1707. bx := i.Method(0).Call([]Value{ValueOf(1000), ValueOf(byte(99))})
  1708. b := bx[0].Interface()
  1709. x := bx[1].Interface()
  1710. if b != byte(99) || x != 1000+inc {
  1711. t.Errorf("direct %s.M(1000, 99) = %v, %v, want 99, %v", name, b, x, 1000+inc)
  1712. }
  1713. CheckF(name+".M", i.Method(0).Interface().(func(int, byte) (byte, int)), inc)
  1714. }
  1715. var TinterType = TypeOf(new(Tinter)).Elem()
  1716. var tinterType = TypeOf(new(tinter)).Elem()
  1717. CheckI := func(name string, i interface{}, inc int) {
  1718. v := ValueOf(i)
  1719. CheckV(name, v, inc)
  1720. CheckV("(i="+name+")", v.Convert(TinterType), inc)
  1721. }
  1722. sv := Tsmallv(1)
  1723. CheckI("sv", sv, 1)
  1724. CheckI("&sv", &sv, 1)
  1725. sp := Tsmallp(2)
  1726. CheckI("&sp", &sp, 2)
  1727. wv := Twordv(3)
  1728. CheckI("wv", wv, 3)
  1729. CheckI("&wv", &wv, 3)
  1730. wp := Twordp(4)
  1731. CheckI("&wp", &wp, 4)
  1732. bv := Tbigv([2]uintptr{5, 6})
  1733. CheckI("bv", bv, 11)
  1734. CheckI("&bv", &bv, 11)
  1735. bp := Tbigp([2]uintptr{7, 8})
  1736. CheckI("&bp", &bp, 15)
  1737. t4 := Tm4{}
  1738. t3 := Tm3{&t4}
  1739. t2 := Tm2{&t3}
  1740. t1 := Tm1{t2}
  1741. CheckI("t4", t4, 40)
  1742. CheckI("&t4", &t4, 40)
  1743. CheckI("t3", t3, 40)
  1744. CheckI("&t3", &t3, 40)
  1745. CheckI("t2", t2, 40)
  1746. CheckI("&t2", &t2, 40)
  1747. CheckI("t1", t1, 40)
  1748. CheckI("&t1", &t1, 40)
  1749. methodShouldPanic := func(name string, i interface{}) {
  1750. v := ValueOf(i)
  1751. m := v.Method(0)
  1752. shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
  1753. shouldPanic(func() { m.Interface() })
  1754. v = v.Convert(tinterType)
  1755. m = v.Method(0)
  1756. shouldPanic(func() { m.Call([]Value{ValueOf(1000), ValueOf(byte(99))}) })
  1757. shouldPanic(func() { m.Interface() })
  1758. }
  1759. _sv := tsmallv(1)
  1760. methodShouldPanic("_sv", _sv)
  1761. methodShouldPanic("&_sv", &_sv)
  1762. _sp := tsmallp(2)
  1763. methodShouldPanic("&_sp", &_sp)
  1764. _wv := twordv(3)
  1765. methodShouldPanic("_wv", _wv)
  1766. methodShouldPanic("&_wv", &_wv)
  1767. _wp := twordp(4)
  1768. methodShouldPanic("&_wp", &_wp)
  1769. _bv := tbigv([2]uintptr{5, 6})
  1770. methodShouldPanic("_bv", _bv)
  1771. methodShouldPanic("&_bv", &_bv)
  1772. _bp := tbigp([2]uintptr{7, 8})
  1773. methodShouldPanic("&_bp", &_bp)
  1774. var tnil Tinter
  1775. vnil := ValueOf(&tnil).Elem()
  1776. shouldPanic(func() { vnil.Method(0) })
  1777. }
  1778. func TestInterfaceSet(t *testing.T) {
  1779. p := &Point{3, 4}
  1780. var s struct {
  1781. I interface{}
  1782. P interface {
  1783. Dist(int) int
  1784. }
  1785. }
  1786. sv := ValueOf(&s).Elem()
  1787. sv.Field(0).Set(ValueOf(p))
  1788. if q := s.I.(*Point); q != p {
  1789. t.Errorf("i: have %p want %p", q, p)
  1790. }
  1791. pv := sv.Field(1)
  1792. pv.Set(ValueOf(p))
  1793. if q := s.P.(*Point); q != p {
  1794. t.Errorf("i: have %p want %p", q, p)
  1795. }
  1796. i := pv.Method(0).Call([]Value{ValueOf(10)})[0].Int()
  1797. if i != 250 {
  1798. t.Errorf("Interface Method returned %d; want 250", i)
  1799. }
  1800. }
  1801. type T1 struct {
  1802. a string
  1803. int
  1804. }
  1805. func TestAnonymousFields(t *testing.T) {
  1806. var field StructField
  1807. var ok bool
  1808. var t1 T1
  1809. type1 := TypeOf(t1)
  1810. if field, ok = type1.FieldByName("int"); !ok {
  1811. t.Fatal("no field 'int'")
  1812. }
  1813. if field.Index[0] != 1 {
  1814. t.Error("field index should be 1; is", field.Index)
  1815. }
  1816. }
  1817. type FTest struct {
  1818. s interface{}
  1819. name string
  1820. index []int
  1821. value int
  1822. }
  1823. type D1 struct {
  1824. d int
  1825. }
  1826. type D2 struct {
  1827. d int
  1828. }
  1829. type S0 struct {
  1830. A, B, C int
  1831. D1
  1832. D2
  1833. }
  1834. type S1 struct {
  1835. B int
  1836. S0
  1837. }
  1838. type S2 struct {
  1839. A int
  1840. *S1
  1841. }
  1842. type S1x struct {
  1843. S1
  1844. }
  1845. type S1y struct {
  1846. S1
  1847. }
  1848. type S3 struct {
  1849. S1x
  1850. S2
  1851. D, E int
  1852. *S1y
  1853. }
  1854. type S4 struct {
  1855. *S4
  1856. A int
  1857. }
  1858. // The X in S6 and S7 annihilate, but they also block the X in S8.S9.
  1859. type S5 struct {
  1860. S6
  1861. S7
  1862. S8
  1863. }
  1864. type S6 struct {
  1865. X int
  1866. }
  1867. type S7 S6
  1868. type S8 struct {
  1869. S9
  1870. }
  1871. type S9 struct {
  1872. X int
  1873. Y int
  1874. }
  1875. // The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9.
  1876. type S10 struct {
  1877. S11
  1878. S12
  1879. S13
  1880. }
  1881. type S11 struct {
  1882. S6
  1883. }
  1884. type S12 struct {
  1885. S6
  1886. }
  1887. type S13 struct {
  1888. S8
  1889. }
  1890. // The X in S15.S11.S1 and S16.S11.S1 annihilate.
  1891. type S14 struct {
  1892. S15
  1893. S16
  1894. }
  1895. type S15 struct {
  1896. S11
  1897. }
  1898. type S16 struct {
  1899. S11
  1900. }
  1901. var fieldTests = []FTest{
  1902. {struct{}{}, "", nil, 0},
  1903. {struct{}{}, "Foo", nil, 0},
  1904. {S0{A: 'a'}, "A", []int{0}, 'a'},
  1905. {S0{}, "D", nil, 0},
  1906. {S1{S0: S0{A: 'a'}}, "A", []int{1, 0}, 'a'},
  1907. {S1{B: 'b'}, "B", []int{0}, 'b'},
  1908. {S1{}, "S0", []int{1}, 0},
  1909. {S1{S0: S0{C: 'c'}}, "C", []int{1, 2}, 'c'},
  1910. {S2{A: 'a'}, "A", []int{0}, 'a'},
  1911. {S2{}, "S1", []int{1}, 0},
  1912. {S2{S1: &S1{B: 'b'}}, "B", []int{1, 0}, 'b'},
  1913. {S2{S1: &S1{S0: S0{C: 'c'}}}, "C", []int{1, 1, 2}, 'c'},
  1914. {S2{}, "D", nil, 0},
  1915. {S3{}, "S1", nil, 0},
  1916. {S3{S2: S2{A: 'a'}}, "A", []int{1, 0}, 'a'},
  1917. {S3{}, "B", nil, 0},
  1918. {S3{D: 'd'}, "D", []int{2}, 0},
  1919. {S3{E: 'e'}, "E", []int{3}, 'e'},
  1920. {S4{A: 'a'}, "A", []int{1}, 'a'},
  1921. {S4{}, "B", nil, 0},
  1922. {S5{}, "X", nil, 0},
  1923. {S5{}, "Y", []int{2, 0, 1}, 0},
  1924. {S10{}, "X", nil, 0},
  1925. {S10{}, "Y", []int{2, 0, 0, 1}, 0},
  1926. {S14{}, "X", nil, 0},
  1927. }
  1928. func TestFieldByIndex(t *testing.T) {
  1929. for _, test := range fieldTests {
  1930. s := TypeOf(test.s)
  1931. f := s.FieldByIndex(test.index)
  1932. if f.Name != "" {
  1933. if test.index != nil {
  1934. if f.Name != test.name {
  1935. t.Errorf("%s.%s found; want %s", s.Name(), f.Name, test.name)
  1936. }
  1937. } else {
  1938. t.Errorf("%s.%s found", s.Name(), f.Name)
  1939. }
  1940. } else if len(test.index) > 0 {
  1941. t.Errorf("%s.%s not found", s.Name(), test.name)
  1942. }
  1943. if test.value != 0 {
  1944. v := ValueOf(test.s).FieldByIndex(test.index)
  1945. if v.IsValid() {
  1946. if x, ok := v.Interface().(int); ok {
  1947. if x != test.value {
  1948. t.Errorf("%s%v is %d; want %d", s.Name(), test.index, x, test.value)
  1949. }
  1950. } else {
  1951. t.Errorf("%s%v value not an int", s.Name(), test.index)
  1952. }
  1953. } else {
  1954. t.Errorf("%s%v value not found", s.Name(), test.index)
  1955. }
  1956. }
  1957. }
  1958. }
  1959. func TestFieldByName(t *testing.T) {
  1960. for _, test := range fieldTests {
  1961. s := TypeOf(test.s)
  1962. f, found := s.FieldByName(test.name)
  1963. if found {
  1964. if test.index != nil {
  1965. // Verify field depth and index.
  1966. if len(f.Index) != len(test.index) {
  1967. 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)
  1968. } else {
  1969. for i, x := range f.Index {
  1970. if x != test.index[i] {
  1971. t.Errorf("%s.%s.Index[%d] is %d; want %d", s.Name(), test.name, i, x, test.index[i])
  1972. }
  1973. }
  1974. }
  1975. } else {
  1976. t.Errorf("%s.%s found", s.Name(), f.Name)
  1977. }
  1978. } else if len(test.index) > 0 {
  1979. t.Errorf("%s.%s not found", s.Name(), test.name)
  1980. }
  1981. if test.value != 0 {
  1982. v := ValueOf(test.s).FieldByName(test.name)
  1983. if v.IsValid() {
  1984. if x, ok := v.Interface().(int); ok {
  1985. if x != test.value {
  1986. t.Errorf("%s.%s is %d; want %d", s.Name(), test.name, x, test.value)
  1987. }
  1988. } else {
  1989. t.Errorf("%s.%s value not an int", s.Name(), test.name)
  1990. }
  1991. } else {
  1992. t.Errorf("%s.%s value not found", s.Name(), test.name)
  1993. }
  1994. }
  1995. }
  1996. }
  1997. func TestImportPath(t *testing.T) {
  1998. tests := []struct {
  1999. t Type
  2000. path string
  2001. }{
  2002. {TypeOf(&base64.Encoding{}).Elem(), "encoding/base64"},
  2003. {TypeOf(int(0)), ""},
  2004. {TypeOf(int8(0)), ""},
  2005. {TypeOf(int16(0)), ""},
  2006. {TypeOf(int32(0)), ""},
  2007. {TypeOf(int64(0)), ""},
  2008. {TypeOf(uint(0)), ""},
  2009. {TypeOf(uint8(0)), ""},
  2010. {TypeOf(uint16(0)), ""},
  2011. {TypeOf(uint32(0)), ""},
  2012. {TypeOf(uint64(0)), ""},
  2013. {TypeOf(uintptr(0)), ""},
  2014. {TypeOf(float32(0)), ""},
  2015. {TypeOf(float64(0)), ""},
  2016. {TypeOf(complex64(0)), ""},
  2017. {TypeOf(complex128(0)), ""},
  2018. {TypeOf(byte(0)), ""},
  2019. {TypeOf(rune(0)), ""},
  2020. {TypeOf([]byte(nil)), ""},
  2021. {TypeOf([]rune(nil)), ""},
  2022. {TypeOf(string("")), ""},
  2023. {TypeOf((*interface{})(nil)).Elem(), ""},
  2024. {TypeOf((*byte)(nil)), ""},
  2025. {TypeOf((*rune)(nil)), ""},
  2026. {TypeOf((*int64)(nil)), ""},
  2027. {TypeOf(map[string]int{}), ""},
  2028. {TypeOf((*error)(nil)).Elem(), ""},
  2029. }
  2030. for _, test := range tests {
  2031. if path := test.t.PkgPath(); path != test.path {
  2032. t.Errorf("%v.PkgPath() = %q, want %q", test.t, path, test.path)
  2033. }
  2034. }
  2035. }
  2036. func TestVariadicType(t *testing.T) {
  2037. // Test example from Type documentation.
  2038. var f func(x int, y ...float64)
  2039. typ := TypeOf(f)
  2040. if typ.NumIn() == 2 && typ.In(0) == TypeOf(int(0)) {
  2041. sl := typ.In(1)
  2042. if sl.Kind() == Slice {
  2043. if sl.Elem() == TypeOf(0.0) {
  2044. // ok
  2045. return
  2046. }
  2047. }
  2048. }
  2049. // Failed
  2050. t.Errorf("want NumIn() = 2, In(0) = int, In(1) = []float64")
  2051. s := fmt.Sprintf("have NumIn() = %d", typ.NumIn())
  2052. for i := 0; i < typ.NumIn(); i++ {
  2053. s += fmt.Sprintf(", In(%d) = %s", i, typ.In(i))
  2054. }
  2055. t.Error(s)
  2056. }
  2057. type inner struct {
  2058. x int
  2059. }
  2060. type outer struct {
  2061. y int
  2062. inner
  2063. }
  2064. func (*inner) m() {}
  2065. func (*outer) m() {}
  2066. func TestNestedMethods(t *testing.T) {
  2067. t.Skip("fails on gccgo due to function wrappers")
  2068. typ := TypeOf((*outer)(nil))
  2069. if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*outer).m).Pointer() {
  2070. t.Errorf("Wrong method table for outer: (m=%p)", (*outer).m)
  2071. for i := 0; i < typ.NumMethod(); i++ {
  2072. m := typ.Method(i)
  2073. t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2074. }
  2075. }
  2076. }
  2077. type InnerInt struct {
  2078. X int
  2079. }
  2080. type OuterInt struct {
  2081. Y int
  2082. InnerInt
  2083. }
  2084. func (i *InnerInt) M() int {
  2085. return i.X
  2086. }
  2087. func TestEmbeddedMethods(t *testing.T) {
  2088. /* This part of the test fails on gccgo due to function wrappers.
  2089. typ := TypeOf((*OuterInt)(nil))
  2090. if typ.NumMethod() != 1 || typ.Method(0).Func.Pointer() != ValueOf((*OuterInt).M).Pointer() {
  2091. t.Errorf("Wrong method table for OuterInt: (m=%p)", (*OuterInt).M)
  2092. for i := 0; i < typ.NumMethod(); i++ {
  2093. m := typ.Method(i)
  2094. t.Errorf("\t%d: %s %#x\n", i, m.Name, m.Func.Pointer())
  2095. }
  2096. }
  2097. */
  2098. i := &InnerInt{3}
  2099. if v := ValueOf(i).Method(0).Call(nil)[0].Int(); v != 3 {
  2100. t.Errorf("i.M() = %d, want 3", v)
  2101. }
  2102. o := &OuterInt{1, InnerInt{2}}
  2103. if v := ValueOf(o).Method(0).Call(nil)[0].Int(); v != 2 {
  2104. t.Errorf("i.M() = %d, want 2", v)
  2105. }
  2106. f := (*OuterInt).M
  2107. if v := f(o); v != 2 {
  2108. t.Errorf("f(o) = %d, want 2", v)
  2109. }
  2110. }
  2111. func TestPtrTo(t *testing.T) {
  2112. var i int
  2113. typ := TypeOf(i)
  2114. for i = 0; i < 100; i++ {
  2115. typ = PtrTo(typ)
  2116. }
  2117. for i = 0; i < 100; i++ {
  2118. typ = typ.Elem()
  2119. }
  2120. if typ != TypeOf(i) {
  2121. t.Errorf("after 100 PtrTo and Elem, have %s, want %s", typ, TypeOf(i))
  2122. }
  2123. }
  2124. func TestPtrToGC(t *testing.T) {
  2125. type T *uintptr
  2126. tt := TypeOf(T(nil))
  2127. pt := PtrTo(tt)
  2128. const n = 100
  2129. var x []interface{}
  2130. for i := 0; i < n; i++ {
  2131. v := New(pt)
  2132. p := new(*uintptr)
  2133. *p = new(uintptr)
  2134. **p = uintptr(i)
  2135. v.Elem().Set(ValueOf(p).Convert(pt))
  2136. x = append(x, v.Interface())
  2137. }
  2138. runtime.GC()
  2139. for i, xi := range x {
  2140. k := ValueOf(xi).Elem().Elem().Elem().Interface().(uintptr)
  2141. if k != uintptr(i) {
  2142. t.Errorf("lost x[%d] = %d, want %d", i, k, i)
  2143. }
  2144. }
  2145. }
  2146. func TestAddr(t *testing.T) {
  2147. var p struct {
  2148. X, Y int
  2149. }
  2150. v := ValueOf(&p)
  2151. v = v.Elem()
  2152. v = v.Addr()
  2153. v = v.Elem()
  2154. v = v.Field(0)
  2155. v.SetInt(2)
  2156. if p.X != 2 {
  2157. t.Errorf("Addr.Elem.Set failed to set value")
  2158. }
  2159. // Again but take address of the ValueOf value.
  2160. // Exercises generation of PtrTypes not present in the binary.
  2161. q := &p
  2162. v = ValueOf(&q).Elem()
  2163. v = v.Addr()
  2164. v = v.Elem()
  2165. v = v.Elem()
  2166. v = v.Addr()
  2167. v = v.Elem()
  2168. v = v.Field(0)
  2169. v.SetInt(3)
  2170. if p.X != 3 {
  2171. t.Errorf("Addr.Elem.Set failed to set value")
  2172. }
  2173. // Starting without pointer we should get changed value
  2174. // in interface.
  2175. qq := p
  2176. v = ValueOf(&qq).Elem()
  2177. v0 := v
  2178. v = v.Addr()
  2179. v = v.Elem()
  2180. v = v.Field(0)
  2181. v.SetInt(4)
  2182. if p.X != 3 { // should be unchanged from last time
  2183. t.Errorf("somehow value Set changed original p")
  2184. }
  2185. p = v0.Interface().(struct {
  2186. X, Y int
  2187. })
  2188. if p.X != 4 {
  2189. t.Errorf("Addr.Elem.Set valued to set value in top value")
  2190. }
  2191. // Verify that taking the address of a type gives us a pointer
  2192. // which we can convert back using the usual interface
  2193. // notation.
  2194. var s struct {
  2195. B *bool
  2196. }
  2197. ps := ValueOf(&s).Elem().Field(0).Addr().Interface()
  2198. *(ps.(**bool)) = new(bool)
  2199. if s.B == nil {
  2200. t.Errorf("Addr.Interface direct assignment failed")
  2201. }
  2202. }
  2203. /* gccgo does do allocations here.
  2204. func noAlloc(t *testing.T, n int, f func(int)) {
  2205. if testing.Short() {
  2206. t.Skip("skipping malloc count in short mode")
  2207. }
  2208. if runtime.GOMAXPROCS(0) > 1 {
  2209. t.Skip("skipping; GOMAXPROCS>1")
  2210. }
  2211. i := -1
  2212. allocs := testing.AllocsPerRun(n, func() {
  2213. f(i)
  2214. i++
  2215. })
  2216. if allocs > 0 {
  2217. t.Errorf("%d iterations: got %v mallocs, want 0", n, allocs)
  2218. }
  2219. }
  2220. func TestAllocations(t *testing.T) {
  2221. noAlloc(t, 100, func(j int) {
  2222. var i interface{}
  2223. var v Value
  2224. // We can uncomment this when compiler escape analysis
  2225. // is good enough to see that the integer assigned to i
  2226. // does not escape and therefore need not be allocated.
  2227. //
  2228. // i = 42 + j
  2229. // v = ValueOf(i)
  2230. // if int(v.Int()) != 42+j {
  2231. // panic("wrong int")
  2232. // }
  2233. i = func(j int) int { return j }
  2234. v = ValueOf(i)
  2235. if v.Interface().(func(int) int)(j) != j {
  2236. panic("wrong result")
  2237. }
  2238. })
  2239. }
  2240. */
  2241. func TestSmallNegativeInt(t *testing.T) {
  2242. i := int16(-1)
  2243. v := ValueOf(i)
  2244. if v.Int() != -1 {
  2245. t.Errorf("int16(-1).Int() returned %v", v.Int())
  2246. }
  2247. }
  2248. func TestIndex(t *testing.T) {
  2249. xs := []byte{1, 2, 3, 4, 5, 6, 7, 8}
  2250. v := ValueOf(xs).Index(3).Interface().(byte)
  2251. if v != xs[3] {
  2252. t.Errorf("xs.Index(3) = %v; expected %v", v, xs[3])
  2253. }
  2254. xa := [8]byte{10, 20, 30, 40, 50, 60, 70, 80}
  2255. v = ValueOf(xa).Index(2).Interface().(byte)
  2256. if v != xa[2] {
  2257. t.Errorf("xa.Index(2) = %v; expected %v", v, xa[2])
  2258. }
  2259. s := "0123456789"
  2260. v = ValueOf(s).Index(3).Interface().(byte)
  2261. if v != s[3] {
  2262. t.Errorf("s.Index(3) = %v; expected %v", v, s[3])
  2263. }
  2264. }
  2265. func TestSlice(t *testing.T) {
  2266. xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2267. v := ValueOf(xs).Slice(3, 5).Interface().([]int)
  2268. if len(v) != 2 {
  2269. t.Errorf("len(xs.Slice(3, 5)) = %d", len(v))
  2270. }
  2271. if cap(v) != 5 {
  2272. t.Errorf("cap(xs.Slice(3, 5)) = %d", cap(v))
  2273. }
  2274. if !DeepEqual(v[0:5], xs[3:]) {
  2275. t.Errorf("xs.Slice(3, 5)[0:5] = %v", v[0:5])
  2276. }
  2277. xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2278. v = ValueOf(&xa).Elem().Slice(2, 5).Interface().([]int)
  2279. if len(v) != 3 {
  2280. t.Errorf("len(xa.Slice(2, 5)) = %d", len(v))
  2281. }
  2282. if cap(v) != 6 {
  2283. t.Errorf("cap(xa.Slice(2, 5)) = %d", cap(v))
  2284. }
  2285. if !DeepEqual(v[0:6], xa[2:]) {
  2286. t.Errorf("xs.Slice(2, 5)[0:6] = %v", v[0:6])
  2287. }
  2288. s := "0123456789"
  2289. vs := ValueOf(s).Slice(3, 5).Interface().(string)
  2290. if vs != s[3:5] {
  2291. t.Errorf("s.Slice(3, 5) = %q; expected %q", vs, s[3:5])
  2292. }
  2293. rv := ValueOf(&xs).Elem()
  2294. rv = rv.Slice(3, 4)
  2295. ptr2 := rv.Pointer()
  2296. rv = rv.Slice(5, 5)
  2297. ptr3 := rv.Pointer()
  2298. if ptr3 != ptr2 {
  2299. t.Errorf("xs.Slice(3,4).Slice3(5,5).Pointer() = %#x, want %#x", ptr3, ptr2)
  2300. }
  2301. }
  2302. func TestSlice3(t *testing.T) {
  2303. xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2304. v := ValueOf(xs).Slice3(3, 5, 7).Interface().([]int)
  2305. if len(v) != 2 {
  2306. t.Errorf("len(xs.Slice3(3, 5, 7)) = %d", len(v))
  2307. }
  2308. if cap(v) != 4 {
  2309. t.Errorf("cap(xs.Slice3(3, 5, 7)) = %d", cap(v))
  2310. }
  2311. if !DeepEqual(v[0:4], xs[3:7:7]) {
  2312. t.Errorf("xs.Slice3(3, 5, 7)[0:4] = %v", v[0:4])
  2313. }
  2314. rv := ValueOf(&xs).Elem()
  2315. shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2316. shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2317. shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2318. xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2319. v = ValueOf(&xa).Elem().Slice3(2, 5, 6).Interface().([]int)
  2320. if len(v) != 3 {
  2321. t.Errorf("len(xa.Slice(2, 5, 6)) = %d", len(v))
  2322. }
  2323. if cap(v) != 4 {
  2324. t.Errorf("cap(xa.Slice(2, 5, 6)) = %d", cap(v))
  2325. }
  2326. if !DeepEqual(v[0:4], xa[2:6:6]) {
  2327. t.Errorf("xs.Slice(2, 5, 6)[0:4] = %v", v[0:4])
  2328. }
  2329. rv = ValueOf(&xa).Elem()
  2330. shouldPanic(func() { rv.Slice3(1, 2, 1) })
  2331. shouldPanic(func() { rv.Slice3(1, 1, 11) })
  2332. shouldPanic(func() { rv.Slice3(2, 2, 1) })
  2333. s := "hello world"
  2334. rv = ValueOf(&s).Elem()
  2335. shouldPanic(func() { rv.Slice3(1, 2, 3) })
  2336. rv = ValueOf(&xs).Elem()
  2337. rv = rv.Slice3(3, 5, 7)
  2338. ptr2 := rv.Pointer()
  2339. rv = rv.Slice3(4, 4, 4)
  2340. ptr3 := rv.Pointer()
  2341. if ptr3 != ptr2 {
  2342. t.Errorf("xs.Slice3(3,5,7).Slice3(4,4,4).Pointer() = %#x, want %#x", ptr3, ptr2)
  2343. }
  2344. }
  2345. func TestSetLenCap(t *testing.T) {
  2346. xs := []int{1, 2, 3, 4, 5, 6, 7, 8}
  2347. xa := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
  2348. vs := ValueOf(&xs).Elem()
  2349. shouldPanic(func() { vs.SetLen(10) })
  2350. shouldPanic(func() { vs.SetCap(10) })
  2351. shouldPanic(func() { vs.SetLen(-1) })
  2352. shouldPanic(func() { vs.SetCap(-1) })
  2353. shouldPanic(func() { vs.SetCap(6) }) // smaller than len
  2354. vs.SetLen(5)
  2355. if len(xs) != 5 || cap(xs) != 8 {
  2356. t.Errorf("after SetLen(5), len, cap = %d, %d, want 5, 8", len(xs), cap(xs))
  2357. }
  2358. vs.SetCap(6)
  2359. if len(xs) != 5 || cap(xs) != 6 {
  2360. t.Errorf("after SetCap(6), len, cap = %d, %d, want 5, 6", len(xs), cap(xs))
  2361. }
  2362. vs.SetCap(5)
  2363. if len(xs) != 5 || cap(xs) != 5 {
  2364. t.Errorf("after SetCap(5), len, cap = %d, %d, want 5, 5", len(xs), cap(xs))
  2365. }
  2366. shouldPanic(func() { vs.SetCap(4) }) // smaller than len
  2367. shouldPanic(func() { vs.SetLen(6) }) // bigger than cap
  2368. va := ValueOf(&xa).Elem()
  2369. shouldPanic(func() { va.SetLen(8) })
  2370. shouldPanic(func() { va.SetCap(8) })
  2371. }
  2372. func TestVariadic(t *testing.T) {
  2373. var b bytes.Buffer
  2374. V := ValueOf
  2375. b.Reset()
  2376. V(fmt.Fprintf).Call([]Value{V(&b), V("%s, %d world"), V("hello"), V(42)})
  2377. if b.String() != "hello, 42 world" {
  2378. t.Errorf("after Fprintf Call: %q != %q", b.String(), "hello 42 world")
  2379. }
  2380. b.Reset()
  2381. V(fmt.Fprintf).CallSlice([]Value{V(&b), V("%s, %d world"), V([]interface{}{"hello", 42})})
  2382. if b.String() != "hello, 42 world" {
  2383. t.Errorf("after Fprintf CallSlice: %q != %q", b.String(), "hello 42 world")
  2384. }
  2385. }
  2386. func TestFuncArg(t *testing.T) {
  2387. f1 := func(i int, f func(int) int) int { return f(i) }
  2388. f2 := func(i int) int { return i + 1 }
  2389. r := ValueOf(f1).Call([]Value{ValueOf(100), ValueOf(f2)})
  2390. if r[0].Int() != 101 {
  2391. t.Errorf("function returned %d, want 101", r[0].Int())
  2392. }
  2393. }
  2394. func TestStructArg(t *testing.T) {
  2395. type padded struct {
  2396. B string
  2397. C int32
  2398. }
  2399. var (
  2400. gotA padded
  2401. gotB uint32
  2402. wantA = padded{"3", 4}
  2403. wantB = uint32(5)
  2404. )
  2405. f := func(a padded, b uint32) {
  2406. gotA, gotB = a, b
  2407. }
  2408. ValueOf(f).Call([]Value{ValueOf(wantA), ValueOf(wantB)})
  2409. if gotA != wantA || gotB != wantB {
  2410. t.Errorf("function called with (%v, %v), want (%v, %v)", gotA, gotB, wantA, wantB)
  2411. }
  2412. }
  2413. var tagGetTests = []struct {
  2414. Tag StructTag
  2415. Key string
  2416. Value string
  2417. }{
  2418. {`protobuf:"PB(1,2)"`, `protobuf`, `PB(1,2)`},
  2419. {`protobuf:"PB(1,2)"`, `foo`, ``},
  2420. {`protobuf:"PB(1,2)"`, `rotobuf`, ``},
  2421. {`protobuf:"PB(1,2)" json:"name"`, `json`, `name`},
  2422. {`protobuf:"PB(1,2)" json:"name"`, `protobuf`, `PB(1,2)`},
  2423. }
  2424. func TestTagGet(t *testing.T) {
  2425. for _, tt := range tagGetTests {
  2426. if v := tt.Tag.Get(tt.Key); v != tt.Value {
  2427. t.Errorf("StructTag(%#q).Get(%#q) = %#q, want %#q", tt.Tag, tt.Key, v, tt.Value)
  2428. }
  2429. }
  2430. }
  2431. func TestBytes(t *testing.T) {
  2432. type B []byte
  2433. x := B{1, 2, 3, 4}
  2434. y := ValueOf(x).Bytes()
  2435. if !bytes.Equal(x, y) {
  2436. t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  2437. }
  2438. if &x[0] != &y[0] {
  2439. t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  2440. }
  2441. }
  2442. func TestSetBytes(t *testing.T) {
  2443. type B []byte
  2444. var x B
  2445. y := []byte{1, 2, 3, 4}
  2446. ValueOf(&x).Elem().SetBytes(y)
  2447. if !bytes.Equal(x, y) {
  2448. t.Fatalf("ValueOf(%v).Bytes() = %v", x, y)
  2449. }
  2450. if &x[0] != &y[0] {
  2451. t.Errorf("ValueOf(%p).Bytes() = %p", &x[0], &y[0])
  2452. }
  2453. }
  2454. type Private struct {
  2455. x int
  2456. y **int
  2457. }
  2458. func (p *Private) m() {
  2459. }
  2460. type Public struct {
  2461. X int
  2462. Y **int
  2463. }
  2464. func (p *Public) M() {
  2465. }
  2466. func TestUnexported(t *testing.T) {
  2467. var pub Public
  2468. v := ValueOf(&pub)
  2469. isValid(v.Elem().Field(0))
  2470. isValid(v.Elem().Field(1))
  2471. isValid(v.Elem().FieldByName("X"))
  2472. isValid(v.Elem().FieldByName("Y"))
  2473. isValid(v.Type().Method(0).Func)
  2474. isNonNil(v.Elem().Field(0).Interface())
  2475. isNonNil(v.Elem().Field(1).Interface())
  2476. isNonNil(v.Elem().FieldByName("X").Interface())
  2477. isNonNil(v.Elem().FieldByName("Y").Interface())
  2478. isNonNil(v.Type().Method(0).Func.Interface())
  2479. var priv Private
  2480. v = ValueOf(&priv)
  2481. isValid(v.Elem().Field(0))
  2482. isValid(v.Elem().Field(1))
  2483. isValid(v.Elem().FieldByName("x"))
  2484. isValid(v.Elem().FieldByName("y"))
  2485. isValid(v.Type().Method(0).Func)
  2486. shouldPanic(func() { v.Elem().Field(0).Interface() })
  2487. shouldPanic(func() { v.Elem().Field(1).Interface() })
  2488. shouldPanic(func() { v.Elem().FieldByName("x").Interface() })
  2489. shouldPanic(func() { v.Elem().FieldByName("y").Interface() })
  2490. shouldPanic(func() { v.Type().Method(0).Func.Interface() })
  2491. }
  2492. func shouldPanic(f func()) {
  2493. defer func() {
  2494. if recover() == nil {
  2495. panic("did not panic")
  2496. }
  2497. }()
  2498. f()
  2499. }
  2500. func isNonNil(x interface{}) {
  2501. if x == nil {
  2502. panic("nil interface")
  2503. }
  2504. }
  2505. func isValid(v Value) {
  2506. if !v.IsValid() {
  2507. panic("zero Value")
  2508. }
  2509. }
  2510. func TestAlias(t *testing.T) {
  2511. x := string("hello")
  2512. v := ValueOf(&x).Elem()
  2513. oldvalue := v.Interface()
  2514. v.SetString("world")
  2515. newvalue := v.Interface()
  2516. if oldvalue != "hello" || newvalue != "world" {
  2517. t.Errorf("aliasing: old=%q new=%q, want hello, world", oldvalue, newvalue)
  2518. }
  2519. }
  2520. var V = ValueOf
  2521. func EmptyInterfaceV(x interface{}) Value {
  2522. return ValueOf(&x).Elem()
  2523. }
  2524. func ReaderV(x io.Reader) Value {
  2525. return ValueOf(&x).Elem()
  2526. }
  2527. func ReadWriterV(x io.ReadWriter) Value {
  2528. return ValueOf(&x).Elem()
  2529. }
  2530. type Empty struct{}
  2531. type MyString string
  2532. type MyBytes []byte
  2533. type MyRunes []int32
  2534. type MyFunc func()
  2535. type MyByte byte
  2536. var convertTests = []struct {
  2537. in Value
  2538. out Value
  2539. }{
  2540. // numbers
  2541. /*
  2542. Edit .+1,/\*\//-1>cat >/tmp/x.go && go run /tmp/x.go
  2543. package main
  2544. import "fmt"
  2545. var numbers = []string{
  2546. "int8", "uint8", "int16", "uint16",
  2547. "int32", "uint32", "int64", "uint64",
  2548. "int", "uint", "uintptr",
  2549. "float32", "float64",
  2550. }
  2551. func main() {
  2552. // all pairs but in an unusual order,
  2553. // to emit all the int8, uint8 cases
  2554. // before n grows too big.
  2555. n := 1
  2556. for i, f := range numbers {
  2557. for _, g := range numbers[i:] {
  2558. fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", f, n, g, n)
  2559. n++
  2560. if f != g {
  2561. fmt.Printf("\t{V(%s(%d)), V(%s(%d))},\n", g, n, f, n)
  2562. n++
  2563. }
  2564. }
  2565. }
  2566. }
  2567. */
  2568. {V(int8(1)), V(int8(1))},
  2569. {V(int8(2)), V(uint8(2))},
  2570. {V(uint8(3)), V(int8(3))},
  2571. {V(int8(4)), V(int16(4))},
  2572. {V(int16(5)), V(int8(5))},
  2573. {V(int8(6)), V(uint16(6))},
  2574. {V(uint16(7)), V(int8(7))},
  2575. {V(int8(8)), V(int32(8))},
  2576. {V(int32(9)), V(int8(9))},
  2577. {V(int8(10)), V(uint32(10))},
  2578. {V(uint32(11)), V(int8(11))},
  2579. {V(int8(12)), V(int64(12))},
  2580. {V(int64(13)), V(int8(13))},
  2581. {V(int8(14)), V(uint64(14))},
  2582. {V(uint64(15)), V(int8(15))},
  2583. {V(int8(16)), V(int(16))},
  2584. {V(int(17)), V(int8(17))},
  2585. {V(int8(18)), V(uint(18))},
  2586. {V(uint(19)), V(int8(19))},
  2587. {V(int8(20)), V(uintptr(20))},
  2588. {V(uintptr(21)), V(int8(21))},
  2589. {V(int8(22)), V(float32(22))},
  2590. {V(float32(23)), V(int8(23))},
  2591. {V(int8(24)), V(float64(24))},
  2592. {V(float64(25)), V(int8(25))},
  2593. {V(uint8(26)), V(uint8(26))},
  2594. {V(uint8(27)), V(int16(27))},
  2595. {V(int16(28)), V(uint8(28))},
  2596. {V(uint8(29)), V(uint16(29))},
  2597. {V(uint16(30)), V(uint8(30))},
  2598. {V(uint8(31)), V(int32(31))},
  2599. {V(int32(32)), V(uint8(32))},
  2600. {V(uint8(33)), V(uint32(33))},
  2601. {V(uint32(34)), V(uint8(34))},
  2602. {V(uint8(35)), V(int64(35))},
  2603. {V(int64(36)), V(uint8(36))},
  2604. {V(uint8(37)), V(uint64(37))},
  2605. {V(uint64(38)), V(uint8(38))},
  2606. {V(uint8(39)), V(int(39))},
  2607. {V(int(40)), V(uint8(40))},
  2608. {V(uint8(41)), V(uint(41))},
  2609. {V(uint(42)), V(uint8(42))},
  2610. {V(uint8(43)), V(uintptr(43))},
  2611. {V(uintptr(44)), V(uint8(44))},
  2612. {V(uint8(45)), V(float32(45))},
  2613. {V(float32(46)), V(uint8(46))},
  2614. {V(uint8(47)), V(float64(47))},
  2615. {V(float64(48)), V(uint8(48))},
  2616. {V(int16(49)), V(int16(49))},
  2617. {V(int16(50)), V(uint16(50))},
  2618. {V(uint16(51)), V(int16(51))},
  2619. {V(int16(52)), V(int32(52))},
  2620. {V(int32(53)), V(int16(53))},
  2621. {V(int16(54)), V(uint32(54))},
  2622. {V(uint32(55)), V(int16(55))},
  2623. {V(int16(56)), V(int64(56))},
  2624. {V(int64(57)), V(int16(57))},
  2625. {V(int16(58)), V(uint64(58))},
  2626. {V(uint64(59)), V(int16(59))},
  2627. {V(int16(60)), V(int(60))},
  2628. {V(int(61)), V(int16(61))},
  2629. {V(int16(62)), V(uint(62))},
  2630. {V(uint(63)), V(int16(63))},
  2631. {V(int16(64)), V(uintptr(64))},
  2632. {V(uintptr(65)), V(int16(65))},
  2633. {V(int16(66)), V(float32(66))},
  2634. {V(float32(67)), V(int16(67))},
  2635. {V(int16(68)), V(float64(68))},
  2636. {V(float64(69)), V(int16(69))},
  2637. {V(uint16(70)), V(uint16(70))},
  2638. {V(uint16(71)), V(int32(71))},
  2639. {V(int32(72)), V(uint16(72))},
  2640. {V(uint16(73)), V(uint32(73))},
  2641. {V(uint32(74)), V(uint16(74))},
  2642. {V(uint16(75)), V(int64(75))},
  2643. {V(int64(76)), V(uint16(76))},
  2644. {V(uint16(77)), V(uint64(77))},
  2645. {V(uint64(78)), V(uint16(78))},
  2646. {V(uint16(79)), V(int(79))},
  2647. {V(int(80)), V(uint16(80))},
  2648. {V(uint16(81)), V(uint(81))},
  2649. {V(uint(82)), V(uint16(82))},
  2650. {V(uint16(83)), V(uintptr(83))},
  2651. {V(uintptr(84)), V(uint16(84))},
  2652. {V(uint16(85)), V(float32(85))},
  2653. {V(float32(86)), V(uint16(86))},
  2654. {V(uint16(87)), V(float64(87))},
  2655. {V(float64(88)), V(uint16(88))},
  2656. {V(int32(89)), V(int32(89))},
  2657. {V(int32(90)), V(uint32(90))},
  2658. {V(uint32(91)), V(int32(91))},
  2659. {V(int32(92)), V(int64(92))},
  2660. {V(int64(93)), V(int32(93))},
  2661. {V(int32(94)), V(uint64(94))},
  2662. {V(uint64(95)), V(int32(95))},
  2663. {V(int32(96)), V(int(96))},
  2664. {V(int(97)), V(int32(97))},
  2665. {V(int32(98)), V(uint(98))},
  2666. {V(uint(99)), V(int32(99))},
  2667. {V(int32(100)), V(uintptr(100))},
  2668. {V(uintptr(101)), V(int32(101))},
  2669. {V(int32(102)), V(float32(102))},
  2670. {V(float32(103)), V(int32(103))},
  2671. {V(int32(104)), V(float64(104))},
  2672. {V(float64(105)), V(int32(105))},
  2673. {V(uint32(106)), V(uint32(106))},
  2674. {V(uint32(107)), V(int64(107))},
  2675. {V(int64(108)), V(uint32(108))},
  2676. {V(uint32(109)), V(uint64(109))},
  2677. {V(uint64(110)), V(uint32(110))},
  2678. {V(uint32(111)), V(int(111))},
  2679. {V(int(112)), V(uint32(112))},
  2680. {V(uint32(113)), V(uint(113))},
  2681. {V(uint(114)), V(uint32(114))},
  2682. {V(uint32(115)), V(uintptr(115))},
  2683. {V(uintptr(116)), V(uint32(116))},
  2684. {V(uint32(117)), V(float32(117))},
  2685. {V(float32(118)), V(uint32(118))},
  2686. {V(uint32(119)), V(float64(119))},
  2687. {V(float64(120)), V(uint32(120))},
  2688. {V(int64(121)), V(int64(121))},
  2689. {V(int64(122)), V(uint64(122))},
  2690. {V(uint64(123)), V(int64(123))},
  2691. {V(int64(124)), V(int(124))},
  2692. {V(int(125)), V(int64(125))},
  2693. {V(int64(126)), V(uint(126))},
  2694. {V(uint(127)), V(int64(127))},
  2695. {V(int64(128)), V(uintptr(128))},
  2696. {V(uintptr(129)), V(int64(129))},
  2697. {V(int64(130)), V(float32(130))},
  2698. {V(float32(131)), V(int64(131))},
  2699. {V(int64(132)), V(float64(132))},
  2700. {V(float64(133)), V(int64(133))},
  2701. {V(uint64(134)), V(uint64(134))},
  2702. {V(uint64(135)), V(int(135))},
  2703. {V(int(136)), V(uint64(136))},
  2704. {V(uint64(137)), V(uint(137))},
  2705. {V(uint(138)), V(uint64(138))},
  2706. {V(uint64(139)), V(uintptr(139))},
  2707. {V(uintptr(140)), V(uint64(140))},
  2708. {V(uint64(141)), V(float32(141))},
  2709. {V(float32(142)), V(uint64(142))},
  2710. {V(uint64(143)), V(float64(143))},
  2711. {V(float64(144)), V(uint64(144))},
  2712. {V(int(145)), V(int(145))},
  2713. {V(int(146)), V(uint(146))},
  2714. {V(uint(147)), V(int(147))},
  2715. {V(int(148)), V(uintptr(148))},
  2716. {V(uintptr(149)), V(int(149))},
  2717. {V(int(150)), V(float32(150))},
  2718. {V(float32(151)), V(int(151))},
  2719. {V(int(152)), V(float64(152))},
  2720. {V(float64(153)), V(int(153))},
  2721. {V(uint(154)), V(uint(154))},
  2722. {V(uint(155)), V(uintptr(155))},
  2723. {V(uintptr(156)), V(uint(156))},
  2724. {V(uint(157)), V(float32(157))},
  2725. {V(float32(158)), V(uint(158))},
  2726. {V(uint(159)), V(float64(159))},
  2727. {V(float64(160)), V(uint(160))},
  2728. {V(uintptr(161)), V(uintptr(161))},
  2729. {V(uintptr(162)), V(float32(162))},
  2730. {V(float32(163)), V(uintptr(163))},
  2731. {V(uintptr(164)), V(float64(164))},
  2732. {V(float64(165)), V(uintptr(165))},
  2733. {V(float32(166)), V(float32(166))},
  2734. {V(float32(167)), V(float64(167))},
  2735. {V(float64(168)), V(float32(168))},
  2736. {V(float64(169)), V(float64(169))},
  2737. // truncation
  2738. {V(float64(1.5)), V(int(1))},
  2739. // complex
  2740. {V(complex64(1i)), V(complex64(1i))},
  2741. {V(complex64(2i)), V(complex128(2i))},
  2742. {V(complex128(3i)), V(complex64(3i))},
  2743. {V(complex128(4i)), V(complex128(4i))},
  2744. // string
  2745. {V(string("hello")), V(string("hello"))},
  2746. {V(string("bytes1")), V([]byte("bytes1"))},
  2747. {V([]byte("bytes2")), V(string("bytes2"))},
  2748. {V([]byte("bytes3")), V([]byte("bytes3"))},
  2749. {V(string("runes♝")), V([]rune("runes♝"))},
  2750. {V([]rune("runes♕")), V(string("runes♕"))},
  2751. {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  2752. {V(int('a')), V(string("a"))},
  2753. {V(int8('a')), V(string("a"))},
  2754. {V(int16('a')), V(string("a"))},
  2755. {V(int32('a')), V(string("a"))},
  2756. {V(int64('a')), V(string("a"))},
  2757. {V(uint('a')), V(string("a"))},
  2758. {V(uint8('a')), V(string("a"))},
  2759. {V(uint16('a')), V(string("a"))},
  2760. {V(uint32('a')), V(string("a"))},
  2761. {V(uint64('a')), V(string("a"))},
  2762. {V(uintptr('a')), V(string("a"))},
  2763. {V(int(-1)), V(string("\uFFFD"))},
  2764. {V(int8(-2)), V(string("\uFFFD"))},
  2765. {V(int16(-3)), V(string("\uFFFD"))},
  2766. {V(int32(-4)), V(string("\uFFFD"))},
  2767. {V(int64(-5)), V(string("\uFFFD"))},
  2768. {V(uint(0x110001)), V(string("\uFFFD"))},
  2769. {V(uint32(0x110002)), V(string("\uFFFD"))},
  2770. {V(uint64(0x110003)), V(string("\uFFFD"))},
  2771. {V(uintptr(0x110004)), V(string("\uFFFD"))},
  2772. // named string
  2773. {V(MyString("hello")), V(string("hello"))},
  2774. {V(string("hello")), V(MyString("hello"))},
  2775. {V(string("hello")), V(string("hello"))},
  2776. {V(MyString("hello")), V(MyString("hello"))},
  2777. {V(MyString("bytes1")), V([]byte("bytes1"))},
  2778. {V([]byte("bytes2")), V(MyString("bytes2"))},
  2779. {V([]byte("bytes3")), V([]byte("bytes3"))},
  2780. {V(MyString("runes♝")), V([]rune("runes♝"))},
  2781. {V([]rune("runes♕")), V(MyString("runes♕"))},
  2782. {V([]rune("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  2783. {V([]rune("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  2784. {V(MyRunes("runes🙈🙉🙊")), V([]rune("runes🙈🙉🙊"))},
  2785. {V(int('a')), V(MyString("a"))},
  2786. {V(int8('a')), V(MyString("a"))},
  2787. {V(int16('a')), V(MyString("a"))},
  2788. {V(int32('a')), V(MyString("a"))},
  2789. {V(int64('a')), V(MyString("a"))},
  2790. {V(uint('a')), V(MyString("a"))},
  2791. {V(uint8('a')), V(MyString("a"))},
  2792. {V(uint16('a')), V(MyString("a"))},
  2793. {V(uint32('a')), V(MyString("a"))},
  2794. {V(uint64('a')), V(MyString("a"))},
  2795. {V(uintptr('a')), V(MyString("a"))},
  2796. {V(int(-1)), V(MyString("\uFFFD"))},
  2797. {V(int8(-2)), V(MyString("\uFFFD"))},
  2798. {V(int16(-3)), V(MyString("\uFFFD"))},
  2799. {V(int32(-4)), V(MyString("\uFFFD"))},
  2800. {V(int64(-5)), V(MyString("\uFFFD"))},
  2801. {V(uint(0x110001)), V(MyString("\uFFFD"))},
  2802. {V(uint32(0x110002)), V(MyString("\uFFFD"))},
  2803. {V(uint64(0x110003)), V(MyString("\uFFFD"))},
  2804. {V(uintptr(0x110004)), V(MyString("\uFFFD"))},
  2805. // named []byte
  2806. {V(string("bytes1")), V(MyBytes("bytes1"))},
  2807. {V(MyBytes("bytes2")), V(string("bytes2"))},
  2808. {V(MyBytes("bytes3")), V(MyBytes("bytes3"))},
  2809. {V(MyString("bytes1")), V(MyBytes("bytes1"))},
  2810. {V(MyBytes("bytes2")), V(MyString("bytes2"))},
  2811. // named []rune
  2812. {V(string("runes♝")), V(MyRunes("runes♝"))},
  2813. {V(MyRunes("runes♕")), V(string("runes♕"))},
  2814. {V(MyRunes("runes🙈🙉🙊")), V(MyRunes("runes🙈🙉🙊"))},
  2815. {V(MyString("runes♝")), V(MyRunes("runes♝"))},
  2816. {V(MyRunes("runes♕")), V(MyString("runes♕"))},
  2817. // named types and equal underlying types
  2818. {V(new(int)), V(new(integer))},
  2819. {V(new(integer)), V(new(int))},
  2820. {V(Empty{}), V(struct{}{})},
  2821. {V(new(Empty)), V(new(struct{}))},
  2822. {V(struct{}{}), V(Empty{})},
  2823. {V(new(struct{})), V(new(Empty))},
  2824. {V(Empty{}), V(Empty{})},
  2825. {V(MyBytes{}), V([]byte{})},
  2826. {V([]byte{}), V(MyBytes{})},
  2827. {V((func())(nil)), V(MyFunc(nil))},
  2828. {V((MyFunc)(nil)), V((func())(nil))},
  2829. // can convert *byte and *MyByte
  2830. {V((*byte)(nil)), V((*MyByte)(nil))},
  2831. {V((*MyByte)(nil)), V((*byte)(nil))},
  2832. // cannot convert mismatched array sizes
  2833. {V([2]byte{}), V([2]byte{})},
  2834. {V([3]byte{}), V([3]byte{})},
  2835. // cannot convert other instances
  2836. {V((**byte)(nil)), V((**byte)(nil))},
  2837. {V((**MyByte)(nil)), V((**MyByte)(nil))},
  2838. {V((chan byte)(nil)), V((chan byte)(nil))},
  2839. {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  2840. {V(([]byte)(nil)), V(([]byte)(nil))},
  2841. {V(([]MyByte)(nil)), V(([]MyByte)(nil))},
  2842. {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  2843. {V((map[int]MyByte)(nil)), V((map[int]MyByte)(nil))},
  2844. {V((map[byte]int)(nil)), V((map[byte]int)(nil))},
  2845. {V((map[MyByte]int)(nil)), V((map[MyByte]int)(nil))},
  2846. {V([2]byte{}), V([2]byte{})},
  2847. {V([2]MyByte{}), V([2]MyByte{})},
  2848. // other
  2849. {V((***int)(nil)), V((***int)(nil))},
  2850. {V((***byte)(nil)), V((***byte)(nil))},
  2851. {V((***int32)(nil)), V((***int32)(nil))},
  2852. {V((***int64)(nil)), V((***int64)(nil))},
  2853. {V((chan int)(nil)), V((<-chan int)(nil))},
  2854. {V((chan int)(nil)), V((chan<- int)(nil))},
  2855. {V((chan string)(nil)), V((<-chan string)(nil))},
  2856. {V((chan string)(nil)), V((chan<- string)(nil))},
  2857. {V((chan byte)(nil)), V((chan byte)(nil))},
  2858. {V((chan MyByte)(nil)), V((chan MyByte)(nil))},
  2859. {V((map[int]bool)(nil)), V((map[int]bool)(nil))},
  2860. {V((map[int]byte)(nil)), V((map[int]byte)(nil))},
  2861. {V((map[uint]bool)(nil)), V((map[uint]bool)(nil))},
  2862. {V([]uint(nil)), V([]uint(nil))},
  2863. {V([]int(nil)), V([]int(nil))},
  2864. {V(new(interface{})), V(new(interface{}))},
  2865. {V(new(io.Reader)), V(new(io.Reader))},
  2866. {V(new(io.Writer)), V(new(io.Writer))},
  2867. // interfaces
  2868. {V(int(1)), EmptyInterfaceV(int(1))},
  2869. {V(string("hello")), EmptyInterfaceV(string("hello"))},
  2870. {V(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  2871. {ReadWriterV(new(bytes.Buffer)), ReaderV(new(bytes.Buffer))},
  2872. {V(new(bytes.Buffer)), ReadWriterV(new(bytes.Buffer))},
  2873. }
  2874. func TestConvert(t *testing.T) {
  2875. canConvert := map[[2]Type]bool{}
  2876. all := map[Type]bool{}
  2877. for _, tt := range convertTests {
  2878. t1 := tt.in.Type()
  2879. if !t1.ConvertibleTo(t1) {
  2880. t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t1)
  2881. continue
  2882. }
  2883. t2 := tt.out.Type()
  2884. if !t1.ConvertibleTo(t2) {
  2885. t.Errorf("(%s).ConvertibleTo(%s) = false, want true", t1, t2)
  2886. continue
  2887. }
  2888. all[t1] = true
  2889. all[t2] = true
  2890. canConvert[[2]Type{t1, t2}] = true
  2891. // vout1 represents the in value converted to the in type.
  2892. v1 := tt.in
  2893. vout1 := v1.Convert(t1)
  2894. out1 := vout1.Interface()
  2895. if vout1.Type() != tt.in.Type() || !DeepEqual(out1, tt.in.Interface()) {
  2896. t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t1, out1, tt.in.Interface())
  2897. }
  2898. // vout2 represents the in value converted to the out type.
  2899. vout2 := v1.Convert(t2)
  2900. out2 := vout2.Interface()
  2901. if vout2.Type() != tt.out.Type() || !DeepEqual(out2, tt.out.Interface()) {
  2902. t.Errorf("ValueOf(%T(%[1]v)).Convert(%s) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out2, tt.out.Interface())
  2903. }
  2904. // vout3 represents a new value of the out type, set to vout2. This makes
  2905. // sure the converted value vout2 is really usable as a regular value.
  2906. vout3 := New(t2).Elem()
  2907. vout3.Set(vout2)
  2908. out3 := vout3.Interface()
  2909. if vout3.Type() != tt.out.Type() || !DeepEqual(out3, tt.out.Interface()) {
  2910. t.Errorf("Set(ValueOf(%T(%[1]v)).Convert(%s)) = %T(%[3]v), want %T(%[4]v)", tt.in.Interface(), t2, out3, tt.out.Interface())
  2911. }
  2912. if IsRO(v1) {
  2913. t.Errorf("table entry %v is RO, should not be", v1)
  2914. }
  2915. if IsRO(vout1) {
  2916. t.Errorf("self-conversion output %v is RO, should not be", vout1)
  2917. }
  2918. if IsRO(vout2) {
  2919. t.Errorf("conversion output %v is RO, should not be", vout2)
  2920. }
  2921. if IsRO(vout3) {
  2922. t.Errorf("set(conversion output) %v is RO, should not be", vout3)
  2923. }
  2924. if !IsRO(MakeRO(v1).Convert(t1)) {
  2925. t.Errorf("RO self-conversion output %v is not RO, should be", v1)
  2926. }
  2927. if !IsRO(MakeRO(v1).Convert(t2)) {
  2928. t.Errorf("RO conversion output %v is not RO, should be", v1)
  2929. }
  2930. }
  2931. // Assume that of all the types we saw during the tests,
  2932. // if there wasn't an explicit entry for a conversion between
  2933. // a pair of types, then it's not to be allowed. This checks for
  2934. // things like 'int64' converting to '*int'.
  2935. for t1 := range all {
  2936. for t2 := range all {
  2937. expectOK := t1 == t2 || canConvert[[2]Type{t1, t2}] || t2.Kind() == Interface && t2.NumMethod() == 0
  2938. if ok := t1.ConvertibleTo(t2); ok != expectOK {
  2939. t.Errorf("(%s).ConvertibleTo(%s) = %v, want %v", t1, t2, ok, expectOK)
  2940. }
  2941. }
  2942. }
  2943. }
  2944. type ComparableStruct struct {
  2945. X int
  2946. }
  2947. type NonComparableStruct struct {
  2948. X int
  2949. Y map[string]int
  2950. }
  2951. var comparableTests = []struct {
  2952. typ Type
  2953. ok bool
  2954. }{
  2955. {TypeOf(1), true},
  2956. {TypeOf("hello"), true},
  2957. {TypeOf(new(byte)), true},
  2958. {TypeOf((func())(nil)), false},
  2959. {TypeOf([]byte{}), false},
  2960. {TypeOf(map[string]int{}), false},
  2961. {TypeOf(make(chan int)), true},
  2962. {TypeOf(1.5), true},
  2963. {TypeOf(false), true},
  2964. {TypeOf(1i), true},
  2965. {TypeOf(ComparableStruct{}), true},
  2966. {TypeOf(NonComparableStruct{}), false},
  2967. {TypeOf([10]map[string]int{}), false},
  2968. {TypeOf([10]string{}), true},
  2969. {TypeOf(new(interface{})).Elem(), true},
  2970. }
  2971. func TestComparable(t *testing.T) {
  2972. for _, tt := range comparableTests {
  2973. if ok := tt.typ.Comparable(); ok != tt.ok {
  2974. t.Errorf("TypeOf(%v).Comparable() = %v, want %v", tt.typ, ok, tt.ok)
  2975. }
  2976. }
  2977. }
  2978. func TestOverflow(t *testing.T) {
  2979. if ovf := V(float64(0)).OverflowFloat(1e300); ovf {
  2980. t.Errorf("%v wrongly overflows float64", 1e300)
  2981. }
  2982. maxFloat32 := float64((1<<24 - 1) << (127 - 23))
  2983. if ovf := V(float32(0)).OverflowFloat(maxFloat32); ovf {
  2984. t.Errorf("%v wrongly overflows float32", maxFloat32)
  2985. }
  2986. ovfFloat32 := float64((1<<24-1)<<(127-23) + 1<<(127-52))
  2987. if ovf := V(float32(0)).OverflowFloat(ovfFloat32); !ovf {
  2988. t.Errorf("%v should overflow float32", ovfFloat32)
  2989. }
  2990. if ovf := V(float32(0)).OverflowFloat(-ovfFloat32); !ovf {
  2991. t.Errorf("%v should overflow float32", -ovfFloat32)
  2992. }
  2993. maxInt32 := int64(0x7fffffff)
  2994. if ovf := V(int32(0)).OverflowInt(maxInt32); ovf {
  2995. t.Errorf("%v wrongly overflows int32", maxInt32)
  2996. }
  2997. if ovf := V(int32(0)).OverflowInt(-1 << 31); ovf {
  2998. t.Errorf("%v wrongly overflows int32", -int64(1)<<31)
  2999. }
  3000. ovfInt32 := int64(1 << 31)
  3001. if ovf := V(int32(0)).OverflowInt(ovfInt32); !ovf {
  3002. t.Errorf("%v should overflow int32", ovfInt32)
  3003. }
  3004. maxUint32 := uint64(0xffffffff)
  3005. if ovf := V(uint32(0)).OverflowUint(maxUint32); ovf {
  3006. t.Errorf("%v wrongly overflows uint32", maxUint32)
  3007. }
  3008. ovfUint32 := uint64(1 << 32)
  3009. if ovf := V(uint32(0)).OverflowUint(ovfUint32); !ovf {
  3010. t.Errorf("%v should overflow uint32", ovfUint32)
  3011. }
  3012. }
  3013. func checkSameType(t *testing.T, x, y interface{}) {
  3014. if TypeOf(x) != TypeOf(y) {
  3015. t.Errorf("did not find preexisting type for %s (vs %s)", TypeOf(x), TypeOf(y))
  3016. }
  3017. }
  3018. func TestArrayOf(t *testing.T) {
  3019. // TODO(rsc): Finish ArrayOf and enable-test.
  3020. t.Skip("ArrayOf is not finished (and not exported)")
  3021. // check construction and use of type not in binary
  3022. type T int
  3023. at := ArrayOf(10, TypeOf(T(1)))
  3024. v := New(at).Elem()
  3025. for i := 0; i < v.Len(); i++ {
  3026. v.Index(i).Set(ValueOf(T(i)))
  3027. }
  3028. s := fmt.Sprint(v.Interface())
  3029. want := "[0 1 2 3 4 5 6 7 8 9]"
  3030. if s != want {
  3031. t.Errorf("constructed array = %s, want %s", s, want)
  3032. }
  3033. // check that type already in binary is found
  3034. checkSameType(t, Zero(ArrayOf(5, TypeOf(T(1)))).Interface(), [5]T{})
  3035. }
  3036. func TestSliceOf(t *testing.T) {
  3037. // check construction and use of type not in binary
  3038. type T int
  3039. st := SliceOf(TypeOf(T(1)))
  3040. v := MakeSlice(st, 10, 10)
  3041. runtime.GC()
  3042. for i := 0; i < v.Len(); i++ {
  3043. v.Index(i).Set(ValueOf(T(i)))
  3044. runtime.GC()
  3045. }
  3046. s := fmt.Sprint(v.Interface())
  3047. want := "[0 1 2 3 4 5 6 7 8 9]"
  3048. if s != want {
  3049. t.Errorf("constructed slice = %s, want %s", s, want)
  3050. }
  3051. // check that type already in binary is found
  3052. type T1 int
  3053. checkSameType(t, Zero(SliceOf(TypeOf(T1(1)))).Interface(), []T1{})
  3054. }
  3055. func TestSliceOverflow(t *testing.T) {
  3056. // check that MakeSlice panics when size of slice overflows uint
  3057. const S = 1e6
  3058. s := uint(S)
  3059. l := (1<<(unsafe.Sizeof((*byte)(nil))*8)-1)/s + 1
  3060. if l*s >= s {
  3061. t.Fatal("slice size does not overflow")
  3062. }
  3063. var x [S]byte
  3064. st := SliceOf(TypeOf(x))
  3065. defer func() {
  3066. err := recover()
  3067. if err == nil {
  3068. t.Fatal("slice overflow does not panic")
  3069. }
  3070. }()
  3071. MakeSlice(st, int(l), int(l))
  3072. }
  3073. func TestSliceOfGC(t *testing.T) {
  3074. type T *uintptr
  3075. tt := TypeOf(T(nil))
  3076. st := SliceOf(tt)
  3077. const n = 100
  3078. var x []interface{}
  3079. for i := 0; i < n; i++ {
  3080. v := MakeSlice(st, n, n)
  3081. for j := 0; j < v.Len(); j++ {
  3082. p := new(uintptr)
  3083. *p = uintptr(i*n + j)
  3084. v.Index(j).Set(ValueOf(p).Convert(tt))
  3085. }
  3086. x = append(x, v.Interface())
  3087. }
  3088. runtime.GC()
  3089. for i, xi := range x {
  3090. v := ValueOf(xi)
  3091. for j := 0; j < v.Len(); j++ {
  3092. k := v.Index(j).Elem().Interface()
  3093. if k != uintptr(i*n+j) {
  3094. t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3095. }
  3096. }
  3097. }
  3098. }
  3099. func TestChanOf(t *testing.T) {
  3100. // check construction and use of type not in binary
  3101. type T string
  3102. ct := ChanOf(BothDir, TypeOf(T("")))
  3103. v := MakeChan(ct, 2)
  3104. runtime.GC()
  3105. v.Send(ValueOf(T("hello")))
  3106. runtime.GC()
  3107. v.Send(ValueOf(T("world")))
  3108. runtime.GC()
  3109. sv1, _ := v.Recv()
  3110. sv2, _ := v.Recv()
  3111. s1 := sv1.String()
  3112. s2 := sv2.String()
  3113. if s1 != "hello" || s2 != "world" {
  3114. t.Errorf("constructed chan: have %q, %q, want %q, %q", s1, s2, "hello", "world")
  3115. }
  3116. // check that type already in binary is found
  3117. type T1 int
  3118. checkSameType(t, Zero(ChanOf(BothDir, TypeOf(T1(1)))).Interface(), (chan T1)(nil))
  3119. }
  3120. func TestChanOfGC(t *testing.T) {
  3121. done := make(chan bool, 1)
  3122. go func() {
  3123. select {
  3124. case <-done:
  3125. case <-time.After(5 * time.Second):
  3126. panic("deadlock in TestChanOfGC")
  3127. }
  3128. }()
  3129. defer func() {
  3130. done <- true
  3131. }()
  3132. type T *uintptr
  3133. tt := TypeOf(T(nil))
  3134. ct := ChanOf(BothDir, tt)
  3135. // NOTE: The garbage collector handles allocated channels specially,
  3136. // so we have to save pointers to channels in x; the pointer code will
  3137. // use the gc info in the newly constructed chan type.
  3138. const n = 100
  3139. var x []interface{}
  3140. for i := 0; i < n; i++ {
  3141. v := MakeChan(ct, n)
  3142. for j := 0; j < n; j++ {
  3143. p := new(uintptr)
  3144. *p = uintptr(i*n + j)
  3145. v.Send(ValueOf(p).Convert(tt))
  3146. }
  3147. pv := New(ct)
  3148. pv.Elem().Set(v)
  3149. x = append(x, pv.Interface())
  3150. }
  3151. runtime.GC()
  3152. for i, xi := range x {
  3153. v := ValueOf(xi).Elem()
  3154. for j := 0; j < n; j++ {
  3155. pv, _ := v.Recv()
  3156. k := pv.Elem().Interface()
  3157. if k != uintptr(i*n+j) {
  3158. t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3159. }
  3160. }
  3161. }
  3162. }
  3163. func TestMapOf(t *testing.T) {
  3164. // check construction and use of type not in binary
  3165. type K string
  3166. type V float64
  3167. v := MakeMap(MapOf(TypeOf(K("")), TypeOf(V(0))))
  3168. runtime.GC()
  3169. v.SetMapIndex(ValueOf(K("a")), ValueOf(V(1)))
  3170. runtime.GC()
  3171. s := fmt.Sprint(v.Interface())
  3172. want := "map[a:1]"
  3173. if s != want {
  3174. t.Errorf("constructed map = %s, want %s", s, want)
  3175. }
  3176. // check that type already in binary is found
  3177. checkSameType(t, Zero(MapOf(TypeOf(V(0)), TypeOf(K("")))).Interface(), map[V]K(nil))
  3178. // check that invalid key type panics
  3179. shouldPanic(func() { MapOf(TypeOf((func())(nil)), TypeOf(false)) })
  3180. }
  3181. func TestMapOfGCKeys(t *testing.T) {
  3182. type T *uintptr
  3183. tt := TypeOf(T(nil))
  3184. mt := MapOf(tt, TypeOf(false))
  3185. // NOTE: The garbage collector handles allocated maps specially,
  3186. // so we have to save pointers to maps in x; the pointer code will
  3187. // use the gc info in the newly constructed map type.
  3188. const n = 100
  3189. var x []interface{}
  3190. for i := 0; i < n; i++ {
  3191. v := MakeMap(mt)
  3192. for j := 0; j < n; j++ {
  3193. p := new(uintptr)
  3194. *p = uintptr(i*n + j)
  3195. v.SetMapIndex(ValueOf(p).Convert(tt), ValueOf(true))
  3196. }
  3197. pv := New(mt)
  3198. pv.Elem().Set(v)
  3199. x = append(x, pv.Interface())
  3200. }
  3201. runtime.GC()
  3202. for i, xi := range x {
  3203. v := ValueOf(xi).Elem()
  3204. var out []int
  3205. for _, kv := range v.MapKeys() {
  3206. out = append(out, int(kv.Elem().Interface().(uintptr)))
  3207. }
  3208. sort.Ints(out)
  3209. for j, k := range out {
  3210. if k != i*n+j {
  3211. t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3212. }
  3213. }
  3214. }
  3215. }
  3216. func TestMapOfGCValues(t *testing.T) {
  3217. type T *uintptr
  3218. tt := TypeOf(T(nil))
  3219. mt := MapOf(TypeOf(1), tt)
  3220. // NOTE: The garbage collector handles allocated maps specially,
  3221. // so we have to save pointers to maps in x; the pointer code will
  3222. // use the gc info in the newly constructed map type.
  3223. const n = 100
  3224. var x []interface{}
  3225. for i := 0; i < n; i++ {
  3226. v := MakeMap(mt)
  3227. for j := 0; j < n; j++ {
  3228. p := new(uintptr)
  3229. *p = uintptr(i*n + j)
  3230. v.SetMapIndex(ValueOf(j), ValueOf(p).Convert(tt))
  3231. }
  3232. pv := New(mt)
  3233. pv.Elem().Set(v)
  3234. x = append(x, pv.Interface())
  3235. }
  3236. runtime.GC()
  3237. for i, xi := range x {
  3238. v := ValueOf(xi).Elem()
  3239. for j := 0; j < n; j++ {
  3240. k := v.MapIndex(ValueOf(j)).Elem().Interface().(uintptr)
  3241. if k != uintptr(i*n+j) {
  3242. t.Errorf("lost x[%d][%d] = %d, want %d", i, j, k, i*n+j)
  3243. }
  3244. }
  3245. }
  3246. }
  3247. type B1 struct {
  3248. X int
  3249. Y int
  3250. Z int
  3251. }
  3252. func BenchmarkFieldByName1(b *testing.B) {
  3253. t := TypeOf(B1{})
  3254. for i := 0; i < b.N; i++ {
  3255. t.FieldByName("Z")
  3256. }
  3257. }
  3258. func BenchmarkFieldByName2(b *testing.B) {
  3259. t := TypeOf(S3{})
  3260. for i := 0; i < b.N; i++ {
  3261. t.FieldByName("B")
  3262. }
  3263. }
  3264. type R0 struct {
  3265. *R1
  3266. *R2
  3267. *R3
  3268. *R4
  3269. }
  3270. type R1 struct {
  3271. *R5
  3272. *R6
  3273. *R7
  3274. *R8
  3275. }
  3276. type R2 R1
  3277. type R3 R1
  3278. type R4 R1
  3279. type R5 struct {
  3280. *R9
  3281. *R10
  3282. *R11
  3283. *R12
  3284. }
  3285. type R6 R5
  3286. type R7 R5
  3287. type R8 R5
  3288. type R9 struct {
  3289. *R13
  3290. *R14
  3291. *R15
  3292. *R16
  3293. }
  3294. type R10 R9
  3295. type R11 R9
  3296. type R12 R9
  3297. type R13 struct {
  3298. *R17
  3299. *R18
  3300. *R19
  3301. *R20
  3302. }
  3303. type R14 R13
  3304. type R15 R13
  3305. type R16 R13
  3306. type R17 struct {
  3307. *R21
  3308. *R22
  3309. *R23
  3310. *R24
  3311. }
  3312. type R18 R17
  3313. type R19 R17
  3314. type R20 R17
  3315. type R21 struct {
  3316. X int
  3317. }
  3318. type R22 R21
  3319. type R23 R21
  3320. type R24 R21
  3321. func TestEmbed(t *testing.T) {
  3322. typ := TypeOf(R0{})
  3323. f, ok := typ.FieldByName("X")
  3324. if ok {
  3325. t.Fatalf(`FieldByName("X") should fail, returned %v`, f.Index)
  3326. }
  3327. }
  3328. func BenchmarkFieldByName3(b *testing.B) {
  3329. t := TypeOf(R0{})
  3330. for i := 0; i < b.N; i++ {
  3331. t.FieldByName("X")
  3332. }
  3333. }
  3334. type S struct {
  3335. i1 int64
  3336. i2 int64
  3337. }
  3338. func BenchmarkInterfaceBig(b *testing.B) {
  3339. v := ValueOf(S{})
  3340. for i := 0; i < b.N; i++ {
  3341. v.Interface()
  3342. }
  3343. b.StopTimer()
  3344. }
  3345. func TestAllocsInterfaceBig(t *testing.T) {
  3346. if testing.Short() {
  3347. t.Skip("skipping malloc count in short mode")
  3348. }
  3349. v := ValueOf(S{})
  3350. if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  3351. t.Error("allocs:", allocs)
  3352. }
  3353. }
  3354. func BenchmarkInterfaceSmall(b *testing.B) {
  3355. v := ValueOf(int64(0))
  3356. for i := 0; i < b.N; i++ {
  3357. v.Interface()
  3358. }
  3359. }
  3360. func TestAllocsInterfaceSmall(t *testing.T) {
  3361. if testing.Short() {
  3362. t.Skip("skipping malloc count in short mode")
  3363. }
  3364. v := ValueOf(int64(0))
  3365. if allocs := testing.AllocsPerRun(100, func() { v.Interface() }); allocs > 0 {
  3366. t.Error("allocs:", allocs)
  3367. }
  3368. }
  3369. // An exhaustive is a mechanism for writing exhaustive or stochastic tests.
  3370. // The basic usage is:
  3371. //
  3372. // for x.Next() {
  3373. // ... code using x.Maybe() or x.Choice(n) to create test cases ...
  3374. // }
  3375. //
  3376. // Each iteration of the loop returns a different set of results, until all
  3377. // possible result sets have been explored. It is okay for different code paths
  3378. // to make different method call sequences on x, but there must be no
  3379. // other source of non-determinism in the call sequences.
  3380. //
  3381. // When faced with a new decision, x chooses randomly. Future explorations
  3382. // of that path will choose successive values for the result. Thus, stopping
  3383. // the loop after a fixed number of iterations gives somewhat stochastic
  3384. // testing.
  3385. //
  3386. // Example:
  3387. //
  3388. // for x.Next() {
  3389. // v := make([]bool, x.Choose(4))
  3390. // for i := range v {
  3391. // v[i] = x.Maybe()
  3392. // }
  3393. // fmt.Println(v)
  3394. // }
  3395. //
  3396. // prints (in some order):
  3397. //
  3398. // []
  3399. // [false]
  3400. // [true]
  3401. // [false false]
  3402. // [false true]
  3403. // ...
  3404. // [true true]
  3405. // [false false false]
  3406. // ...
  3407. // [true true true]
  3408. // [false false false false]
  3409. // ...
  3410. // [true true true true]
  3411. //
  3412. type exhaustive struct {
  3413. r *rand.Rand
  3414. pos int
  3415. last []choice
  3416. }
  3417. type choice struct {
  3418. off int
  3419. n int
  3420. max int
  3421. }
  3422. func (x *exhaustive) Next() bool {
  3423. if x.r == nil {
  3424. x.r = rand.New(rand.NewSource(time.Now().UnixNano()))
  3425. }
  3426. x.pos = 0
  3427. if x.last == nil {
  3428. x.last = []choice{}
  3429. return true
  3430. }
  3431. for i := len(x.last) - 1; i >= 0; i-- {
  3432. c := &x.last[i]
  3433. if c.n+1 < c.max {
  3434. c.n++
  3435. x.last = x.last[:i+1]
  3436. return true
  3437. }
  3438. }
  3439. return false
  3440. }
  3441. func (x *exhaustive) Choose(max int) int {
  3442. if x.pos >= len(x.last) {
  3443. x.last = append(x.last, choice{x.r.Intn(max), 0, max})
  3444. }
  3445. c := &x.last[x.pos]
  3446. x.pos++
  3447. if c.max != max {
  3448. panic("inconsistent use of exhaustive tester")
  3449. }
  3450. return (c.n + c.off) % max
  3451. }
  3452. func (x *exhaustive) Maybe() bool {
  3453. return x.Choose(2) == 1
  3454. }
  3455. func GCFunc(args []Value) []Value {
  3456. runtime.GC()
  3457. return []Value{}
  3458. }
  3459. func TestReflectFuncTraceback(t *testing.T) {
  3460. f := MakeFunc(TypeOf(func() {}), GCFunc)
  3461. f.Call([]Value{})
  3462. }
  3463. func TestReflectMethodTraceback(t *testing.T) {
  3464. p := Point{3, 4}
  3465. m := ValueOf(p).MethodByName("GCMethod")
  3466. i := ValueOf(m.Interface()).Call([]Value{ValueOf(5)})[0].Int()
  3467. if i != 8 {
  3468. t.Errorf("Call returned %d; want 8", i)
  3469. }
  3470. }
  3471. func TestBigZero(t *testing.T) {
  3472. const size = 1 << 10
  3473. var v [size]byte
  3474. z := Zero(ValueOf(v).Type()).Interface().([size]byte)
  3475. for i := 0; i < size; i++ {
  3476. if z[i] != 0 {
  3477. t.Fatalf("Zero object not all zero, index %d", i)
  3478. }
  3479. }
  3480. }
  3481. func TestFieldByIndexNil(t *testing.T) {
  3482. type P struct {
  3483. F int
  3484. }
  3485. type T struct {
  3486. *P
  3487. }
  3488. v := ValueOf(T{})
  3489. v.FieldByName("P") // should be fine
  3490. defer func() {
  3491. if err := recover(); err == nil {
  3492. t.Fatalf("no error")
  3493. } else if !strings.Contains(fmt.Sprint(err), "nil pointer to embedded struct") {
  3494. t.Fatalf(`err=%q, wanted error containing "nil pointer to embedded struct"`, err)
  3495. }
  3496. }()
  3497. v.FieldByName("F") // should panic
  3498. t.Fatalf("did not panic")
  3499. }
  3500. // Given
  3501. // type Outer struct {
  3502. // *Inner
  3503. // ...
  3504. // }
  3505. // the compiler generates the implementation of (*Outer).M dispatching to the embedded Inner.
  3506. // The implementation is logically:
  3507. // func (p *Outer) M() {
  3508. // (p.Inner).M()
  3509. // }
  3510. // but since the only change here is the replacement of one pointer receiver with another,
  3511. // the actual generated code overwrites the original receiver with the p.Inner pointer and
  3512. // then jumps to the M method expecting the *Inner receiver.
  3513. //
  3514. // During reflect.Value.Call, we create an argument frame and the associated data structures
  3515. // to describe it to the garbage collector, populate the frame, call reflect.call to
  3516. // run a function call using that frame, and then copy the results back out of the frame.
  3517. // The reflect.call function does a memmove of the frame structure onto the
  3518. // stack (to set up the inputs), runs the call, and the memmoves the stack back to
  3519. // the frame structure (to preserve the outputs).
  3520. //
  3521. // Originally reflect.call did not distinguish inputs from outputs: both memmoves
  3522. // were for the full stack frame. However, in the case where the called function was
  3523. // one of these wrappers, the rewritten receiver is almost certainly a different type
  3524. // than the original receiver. This is not a problem on the stack, where we use the
  3525. // program counter to determine the type information and understand that
  3526. // during (*Outer).M the receiver is an *Outer while during (*Inner).M the receiver in the same
  3527. // memory word is now an *Inner. But in the statically typed argument frame created
  3528. // by reflect, the receiver is always an *Outer. Copying the modified receiver pointer
  3529. // off the stack into the frame will store an *Inner there, and then if a garbage collection
  3530. // happens to scan that argument frame before it is discarded, it will scan the *Inner
  3531. // memory as if it were an *Outer. If the two have different memory layouts, the
  3532. // collection will intepret the memory incorrectly.
  3533. //
  3534. // One such possible incorrect interpretation is to treat two arbitrary memory words
  3535. // (Inner.P1 and Inner.P2 below) as an interface (Outer.R below). Because interpreting
  3536. // an interface requires dereferencing the itab word, the misinterpretation will try to
  3537. // deference Inner.P1, causing a crash during garbage collection.
  3538. //
  3539. // This came up in a real program in issue 7725.
  3540. type Outer struct {
  3541. *Inner
  3542. R io.Reader
  3543. }
  3544. type Inner struct {
  3545. X *Outer
  3546. P1 uintptr
  3547. P2 uintptr
  3548. }
  3549. func (pi *Inner) M() {
  3550. // Clear references to pi so that the only way the
  3551. // garbage collection will find the pointer is in the
  3552. // argument frame, typed as a *Outer.
  3553. pi.X.Inner = nil
  3554. // Set up an interface value that will cause a crash.
  3555. // P1 = 1 is a non-zero, so the interface looks non-nil.
  3556. // P2 = pi ensures that the data word points into the
  3557. // allocated heap; if not the collection skips the interface
  3558. // value as irrelevant, without dereferencing P1.
  3559. pi.P1 = 1
  3560. pi.P2 = uintptr(unsafe.Pointer(pi))
  3561. }
  3562. func TestCallMethodJump(t *testing.T) {
  3563. // In reflect.Value.Call, trigger a garbage collection after reflect.call
  3564. // returns but before the args frame has been discarded.
  3565. // This is a little clumsy but makes the failure repeatable.
  3566. *CallGC = true
  3567. p := &Outer{Inner: new(Inner)}
  3568. p.Inner.X = p
  3569. ValueOf(p).Method(0).Call(nil)
  3570. // Stop garbage collecting during reflect.call.
  3571. *CallGC = false
  3572. }
  3573. func TestMakeFuncStackCopy(t *testing.T) {
  3574. target := func(in []Value) []Value {
  3575. runtime.GC()
  3576. useStack(16)
  3577. return []Value{ValueOf(9)}
  3578. }
  3579. var concrete func(*int, int) int
  3580. fn := MakeFunc(ValueOf(concrete).Type(), target)
  3581. ValueOf(&concrete).Elem().Set(fn)
  3582. x := concrete(nil, 7)
  3583. if x != 9 {
  3584. t.Errorf("have %#q want 9", x)
  3585. }
  3586. }
  3587. // use about n KB of stack
  3588. func useStack(n int) {
  3589. if n == 0 {
  3590. return
  3591. }
  3592. var b [1024]byte // makes frame about 1KB
  3593. useStack(n - 1 + int(b[99]))
  3594. }
  3595. type Impl struct{}
  3596. func (Impl) f() {}
  3597. func TestValueString(t *testing.T) {
  3598. rv := ValueOf(Impl{})
  3599. if rv.String() != "<reflect_test.Impl Value>" {
  3600. t.Errorf("ValueOf(Impl{}).String() = %q, want %q", rv.String(), "<reflect_test.Impl Value>")
  3601. }
  3602. method := rv.Method(0)
  3603. if method.String() != "<func() Value>" {
  3604. t.Errorf("ValueOf(Impl{}).Method(0).String() = %q, want %q", method.String(), "<func() Value>")
  3605. }
  3606. }
  3607. func TestInvalid(t *testing.T) {
  3608. // Used to have inconsistency between IsValid() and Kind() != Invalid.
  3609. type T struct{ v interface{} }
  3610. v := ValueOf(T{}).Field(0)
  3611. if v.IsValid() != true || v.Kind() != Interface {
  3612. t.Errorf("field: IsValid=%v, Kind=%v, want true, Interface", v.IsValid(), v.Kind())
  3613. }
  3614. v = v.Elem()
  3615. if v.IsValid() != false || v.Kind() != Invalid {
  3616. t.Errorf("field elem: IsValid=%v, Kind=%v, want false, Invalid", v.IsValid(), v.Kind())
  3617. }
  3618. }
  3619. // Issue 8917.
  3620. func TestLargeGCProg(t *testing.T) {
  3621. fv := ValueOf(func([256]*byte) {})
  3622. fv.Call([]Value{ValueOf([256]*byte{})})
  3623. }
  3624. // Issue 9179.
  3625. func TestCallGC(t *testing.T) {
  3626. f := func(a, b, c, d, e string) {
  3627. }
  3628. g := func(in []Value) []Value {
  3629. runtime.GC()
  3630. return nil
  3631. }
  3632. typ := ValueOf(f).Type()
  3633. f2 := MakeFunc(typ, g).Interface().(func(string, string, string, string, string))
  3634. f2("four", "five5", "six666", "seven77", "eight888")
  3635. }
  3636. type funcLayoutTest struct {
  3637. rcvr, t Type
  3638. argsize, retOffset uintptr
  3639. stack []byte
  3640. }
  3641. var funcLayoutTests []funcLayoutTest
  3642. func init() {
  3643. var argAlign = PtrSize
  3644. if runtime.GOARCH == "amd64p32" {
  3645. argAlign = 2 * PtrSize
  3646. }
  3647. roundup := func(x uintptr, a uintptr) uintptr {
  3648. return (x + a - 1) / a * a
  3649. }
  3650. funcLayoutTests = append(funcLayoutTests,
  3651. funcLayoutTest{
  3652. nil,
  3653. ValueOf(func(a, b string) string { return "" }).Type(),
  3654. 4 * PtrSize,
  3655. 4 * PtrSize,
  3656. []byte{BitsPointer, BitsScalar, BitsPointer},
  3657. })
  3658. var r []byte
  3659. if PtrSize == 4 {
  3660. r = []byte{BitsScalar, BitsScalar, BitsScalar, BitsPointer}
  3661. } else {
  3662. r = []byte{BitsScalar, BitsScalar, BitsPointer}
  3663. }
  3664. funcLayoutTests = append(funcLayoutTests,
  3665. funcLayoutTest{
  3666. nil,
  3667. ValueOf(func(a, b, c uint32, p *byte, d uint16) {}).Type(),
  3668. roundup(3*4, PtrSize) + PtrSize + 2,
  3669. roundup(roundup(3*4, PtrSize)+PtrSize+2, argAlign),
  3670. r,
  3671. })
  3672. funcLayoutTests = append(funcLayoutTests,
  3673. funcLayoutTest{
  3674. nil,
  3675. ValueOf(func(a map[int]int, b uintptr, c interface{}) {}).Type(),
  3676. 4 * PtrSize,
  3677. 4 * PtrSize,
  3678. []byte{BitsPointer, BitsScalar, BitsPointer, BitsPointer},
  3679. })
  3680. type S struct {
  3681. a, b uintptr
  3682. c, d *byte
  3683. }
  3684. funcLayoutTests = append(funcLayoutTests,
  3685. funcLayoutTest{
  3686. nil,
  3687. ValueOf(func(a S) {}).Type(),
  3688. 4 * PtrSize,
  3689. 4 * PtrSize,
  3690. []byte{BitsScalar, BitsScalar, BitsPointer, BitsPointer},
  3691. })
  3692. funcLayoutTests = append(funcLayoutTests,
  3693. funcLayoutTest{
  3694. ValueOf((*byte)(nil)).Type(),
  3695. ValueOf(func(a uintptr, b *int) {}).Type(),
  3696. 3 * PtrSize,
  3697. roundup(3*PtrSize, argAlign),
  3698. []byte{BitsPointer, BitsScalar, BitsPointer},
  3699. })
  3700. }
  3701. func TestFuncLayout(t *testing.T) {
  3702. t.Skip("gccgo does not use funcLayout")
  3703. for _, lt := range funcLayoutTests {
  3704. _, argsize, retOffset, stack := FuncLayout(lt.t, lt.rcvr)
  3705. if argsize != lt.argsize {
  3706. t.Errorf("funcLayout(%v, %v).argsize=%d, want %d", lt.t, lt.rcvr, argsize, lt.argsize)
  3707. }
  3708. if retOffset != lt.retOffset {
  3709. t.Errorf("funcLayout(%v, %v).retOffset=%d, want %d", lt.t, lt.rcvr, retOffset, lt.retOffset)
  3710. }
  3711. if !bytes.Equal(stack, lt.stack) {
  3712. t.Errorf("funcLayout(%v, %v).stack=%v, want %v", lt.t, lt.rcvr, stack, lt.stack)
  3713. }
  3714. }
  3715. }