codec_test.go 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529
  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 gob
  5. import (
  6. "bytes"
  7. "errors"
  8. "flag"
  9. "math"
  10. "math/rand"
  11. "reflect"
  12. "strings"
  13. "testing"
  14. "time"
  15. )
  16. var doFuzzTests = flag.Bool("gob.fuzz", false, "run the fuzz tests, which are large and very slow")
  17. // Guarantee encoding format by comparing some encodings to hand-written values
  18. type EncodeT struct {
  19. x uint64
  20. b []byte
  21. }
  22. var encodeT = []EncodeT{
  23. {0x00, []byte{0x00}},
  24. {0x0F, []byte{0x0F}},
  25. {0xFF, []byte{0xFF, 0xFF}},
  26. {0xFFFF, []byte{0xFE, 0xFF, 0xFF}},
  27. {0xFFFFFF, []byte{0xFD, 0xFF, 0xFF, 0xFF}},
  28. {0xFFFFFFFF, []byte{0xFC, 0xFF, 0xFF, 0xFF, 0xFF}},
  29. {0xFFFFFFFFFF, []byte{0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
  30. {0xFFFFFFFFFFFF, []byte{0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
  31. {0xFFFFFFFFFFFFFF, []byte{0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
  32. {0xFFFFFFFFFFFFFFFF, []byte{0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}},
  33. {0x1111, []byte{0xFE, 0x11, 0x11}},
  34. {0x1111111111111111, []byte{0xF8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}},
  35. {0x8888888888888888, []byte{0xF8, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}},
  36. {1 << 63, []byte{0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
  37. }
  38. // testError is meant to be used as a deferred function to turn a panic(gobError) into a
  39. // plain test.Error call.
  40. func testError(t *testing.T) {
  41. if e := recover(); e != nil {
  42. t.Error(e.(gobError).err) // Will re-panic if not one of our errors, such as a runtime error.
  43. }
  44. }
  45. func newDecBuffer(data []byte) *decBuffer {
  46. return &decBuffer{
  47. data: data,
  48. }
  49. }
  50. // Test basic encode/decode routines for unsigned integers
  51. func TestUintCodec(t *testing.T) {
  52. defer testError(t)
  53. b := new(encBuffer)
  54. encState := newEncoderState(b)
  55. for _, tt := range encodeT {
  56. b.Reset()
  57. encState.encodeUint(tt.x)
  58. if !bytes.Equal(tt.b, b.Bytes()) {
  59. t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes())
  60. }
  61. }
  62. for u := uint64(0); ; u = (u + 1) * 7 {
  63. b.Reset()
  64. encState.encodeUint(u)
  65. decState := newDecodeState(newDecBuffer(b.Bytes()))
  66. v := decState.decodeUint()
  67. if u != v {
  68. t.Errorf("Encode/Decode: sent %#x received %#x", u, v)
  69. }
  70. if u&(1<<63) != 0 {
  71. break
  72. }
  73. }
  74. }
  75. func verifyInt(i int64, t *testing.T) {
  76. defer testError(t)
  77. var b = new(encBuffer)
  78. encState := newEncoderState(b)
  79. encState.encodeInt(i)
  80. decState := newDecodeState(newDecBuffer(b.Bytes()))
  81. j := decState.decodeInt()
  82. if i != j {
  83. t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j))
  84. }
  85. }
  86. // Test basic encode/decode routines for signed integers
  87. func TestIntCodec(t *testing.T) {
  88. for u := uint64(0); ; u = (u + 1) * 7 {
  89. // Do positive and negative values
  90. i := int64(u)
  91. verifyInt(i, t)
  92. verifyInt(-i, t)
  93. verifyInt(^i, t)
  94. if u&(1<<63) != 0 {
  95. break
  96. }
  97. }
  98. verifyInt(-1<<63, t) // a tricky case
  99. }
  100. // The result of encoding a true boolean with field number 7
  101. var boolResult = []byte{0x07, 0x01}
  102. // The result of encoding a number 17 with field number 7
  103. var signedResult = []byte{0x07, 2 * 17}
  104. var unsignedResult = []byte{0x07, 17}
  105. var floatResult = []byte{0x07, 0xFE, 0x31, 0x40}
  106. // The result of encoding a number 17+19i with field number 7
  107. var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40}
  108. // The result of encoding "hello" with field number 7
  109. var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'}
  110. func newDecodeState(buf *decBuffer) *decoderState {
  111. d := new(decoderState)
  112. d.b = buf
  113. return d
  114. }
  115. func newEncoderState(b *encBuffer) *encoderState {
  116. b.Reset()
  117. state := &encoderState{enc: nil, b: b}
  118. state.fieldnum = -1
  119. return state
  120. }
  121. // Test instruction execution for encoding.
  122. // Do not run the machine yet; instead do individual instructions crafted by hand.
  123. func TestScalarEncInstructions(t *testing.T) {
  124. var b = new(encBuffer)
  125. // bool
  126. {
  127. var data bool = true
  128. instr := &encInstr{encBool, 6, nil, 0}
  129. state := newEncoderState(b)
  130. instr.op(instr, state, reflect.ValueOf(data))
  131. if !bytes.Equal(boolResult, b.Bytes()) {
  132. t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes())
  133. }
  134. }
  135. // int
  136. {
  137. b.Reset()
  138. var data int = 17
  139. instr := &encInstr{encInt, 6, nil, 0}
  140. state := newEncoderState(b)
  141. instr.op(instr, state, reflect.ValueOf(data))
  142. if !bytes.Equal(signedResult, b.Bytes()) {
  143. t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes())
  144. }
  145. }
  146. // uint
  147. {
  148. b.Reset()
  149. var data uint = 17
  150. instr := &encInstr{encUint, 6, nil, 0}
  151. state := newEncoderState(b)
  152. instr.op(instr, state, reflect.ValueOf(data))
  153. if !bytes.Equal(unsignedResult, b.Bytes()) {
  154. t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes())
  155. }
  156. }
  157. // int8
  158. {
  159. b.Reset()
  160. var data int8 = 17
  161. instr := &encInstr{encInt, 6, nil, 0}
  162. state := newEncoderState(b)
  163. instr.op(instr, state, reflect.ValueOf(data))
  164. if !bytes.Equal(signedResult, b.Bytes()) {
  165. t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes())
  166. }
  167. }
  168. // uint8
  169. {
  170. b.Reset()
  171. var data uint8 = 17
  172. instr := &encInstr{encUint, 6, nil, 0}
  173. state := newEncoderState(b)
  174. instr.op(instr, state, reflect.ValueOf(data))
  175. if !bytes.Equal(unsignedResult, b.Bytes()) {
  176. t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
  177. }
  178. }
  179. // int16
  180. {
  181. b.Reset()
  182. var data int16 = 17
  183. instr := &encInstr{encInt, 6, nil, 0}
  184. state := newEncoderState(b)
  185. instr.op(instr, state, reflect.ValueOf(data))
  186. if !bytes.Equal(signedResult, b.Bytes()) {
  187. t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes())
  188. }
  189. }
  190. // uint16
  191. {
  192. b.Reset()
  193. var data uint16 = 17
  194. instr := &encInstr{encUint, 6, nil, 0}
  195. state := newEncoderState(b)
  196. instr.op(instr, state, reflect.ValueOf(data))
  197. if !bytes.Equal(unsignedResult, b.Bytes()) {
  198. t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
  199. }
  200. }
  201. // int32
  202. {
  203. b.Reset()
  204. var data int32 = 17
  205. instr := &encInstr{encInt, 6, nil, 0}
  206. state := newEncoderState(b)
  207. instr.op(instr, state, reflect.ValueOf(data))
  208. if !bytes.Equal(signedResult, b.Bytes()) {
  209. t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes())
  210. }
  211. }
  212. // uint32
  213. {
  214. b.Reset()
  215. var data uint32 = 17
  216. instr := &encInstr{encUint, 6, nil, 0}
  217. state := newEncoderState(b)
  218. instr.op(instr, state, reflect.ValueOf(data))
  219. if !bytes.Equal(unsignedResult, b.Bytes()) {
  220. t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
  221. }
  222. }
  223. // int64
  224. {
  225. b.Reset()
  226. var data int64 = 17
  227. instr := &encInstr{encInt, 6, nil, 0}
  228. state := newEncoderState(b)
  229. instr.op(instr, state, reflect.ValueOf(data))
  230. if !bytes.Equal(signedResult, b.Bytes()) {
  231. t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes())
  232. }
  233. }
  234. // uint64
  235. {
  236. b.Reset()
  237. var data uint64 = 17
  238. instr := &encInstr{encUint, 6, nil, 0}
  239. state := newEncoderState(b)
  240. instr.op(instr, state, reflect.ValueOf(data))
  241. if !bytes.Equal(unsignedResult, b.Bytes()) {
  242. t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes())
  243. }
  244. }
  245. // float32
  246. {
  247. b.Reset()
  248. var data float32 = 17
  249. instr := &encInstr{encFloat, 6, nil, 0}
  250. state := newEncoderState(b)
  251. instr.op(instr, state, reflect.ValueOf(data))
  252. if !bytes.Equal(floatResult, b.Bytes()) {
  253. t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes())
  254. }
  255. }
  256. // float64
  257. {
  258. b.Reset()
  259. var data float64 = 17
  260. instr := &encInstr{encFloat, 6, nil, 0}
  261. state := newEncoderState(b)
  262. instr.op(instr, state, reflect.ValueOf(data))
  263. if !bytes.Equal(floatResult, b.Bytes()) {
  264. t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes())
  265. }
  266. }
  267. // bytes == []uint8
  268. {
  269. b.Reset()
  270. data := []byte("hello")
  271. instr := &encInstr{encUint8Array, 6, nil, 0}
  272. state := newEncoderState(b)
  273. instr.op(instr, state, reflect.ValueOf(data))
  274. if !bytes.Equal(bytesResult, b.Bytes()) {
  275. t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes())
  276. }
  277. }
  278. // string
  279. {
  280. b.Reset()
  281. var data string = "hello"
  282. instr := &encInstr{encString, 6, nil, 0}
  283. state := newEncoderState(b)
  284. instr.op(instr, state, reflect.ValueOf(data))
  285. if !bytes.Equal(bytesResult, b.Bytes()) {
  286. t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes())
  287. }
  288. }
  289. }
  290. func execDec(instr *decInstr, state *decoderState, t *testing.T, value reflect.Value) {
  291. defer testError(t)
  292. v := int(state.decodeUint())
  293. if v+state.fieldnum != 6 {
  294. t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum)
  295. }
  296. instr.op(instr, state, value.Elem())
  297. state.fieldnum = 6
  298. }
  299. func newDecodeStateFromData(data []byte) *decoderState {
  300. b := newDecBuffer(data)
  301. state := newDecodeState(b)
  302. state.fieldnum = -1
  303. return state
  304. }
  305. // Test instruction execution for decoding.
  306. // Do not run the machine yet; instead do individual instructions crafted by hand.
  307. func TestScalarDecInstructions(t *testing.T) {
  308. ovfl := errors.New("overflow")
  309. // bool
  310. {
  311. var data bool
  312. instr := &decInstr{decBool, 6, nil, ovfl}
  313. state := newDecodeStateFromData(boolResult)
  314. execDec(instr, state, t, reflect.ValueOf(&data))
  315. if data != true {
  316. t.Errorf("bool a = %v not true", data)
  317. }
  318. }
  319. // int
  320. {
  321. var data int
  322. instr := &decInstr{decOpTable[reflect.Int], 6, nil, ovfl}
  323. state := newDecodeStateFromData(signedResult)
  324. execDec(instr, state, t, reflect.ValueOf(&data))
  325. if data != 17 {
  326. t.Errorf("int a = %v not 17", data)
  327. }
  328. }
  329. // uint
  330. {
  331. var data uint
  332. instr := &decInstr{decOpTable[reflect.Uint], 6, nil, ovfl}
  333. state := newDecodeStateFromData(unsignedResult)
  334. execDec(instr, state, t, reflect.ValueOf(&data))
  335. if data != 17 {
  336. t.Errorf("uint a = %v not 17", data)
  337. }
  338. }
  339. // int8
  340. {
  341. var data int8
  342. instr := &decInstr{decInt8, 6, nil, ovfl}
  343. state := newDecodeStateFromData(signedResult)
  344. execDec(instr, state, t, reflect.ValueOf(&data))
  345. if data != 17 {
  346. t.Errorf("int8 a = %v not 17", data)
  347. }
  348. }
  349. // uint8
  350. {
  351. var data uint8
  352. instr := &decInstr{decUint8, 6, nil, ovfl}
  353. state := newDecodeStateFromData(unsignedResult)
  354. execDec(instr, state, t, reflect.ValueOf(&data))
  355. if data != 17 {
  356. t.Errorf("uint8 a = %v not 17", data)
  357. }
  358. }
  359. // int16
  360. {
  361. var data int16
  362. instr := &decInstr{decInt16, 6, nil, ovfl}
  363. state := newDecodeStateFromData(signedResult)
  364. execDec(instr, state, t, reflect.ValueOf(&data))
  365. if data != 17 {
  366. t.Errorf("int16 a = %v not 17", data)
  367. }
  368. }
  369. // uint16
  370. {
  371. var data uint16
  372. instr := &decInstr{decUint16, 6, nil, ovfl}
  373. state := newDecodeStateFromData(unsignedResult)
  374. execDec(instr, state, t, reflect.ValueOf(&data))
  375. if data != 17 {
  376. t.Errorf("uint16 a = %v not 17", data)
  377. }
  378. }
  379. // int32
  380. {
  381. var data int32
  382. instr := &decInstr{decInt32, 6, nil, ovfl}
  383. state := newDecodeStateFromData(signedResult)
  384. execDec(instr, state, t, reflect.ValueOf(&data))
  385. if data != 17 {
  386. t.Errorf("int32 a = %v not 17", data)
  387. }
  388. }
  389. // uint32
  390. {
  391. var data uint32
  392. instr := &decInstr{decUint32, 6, nil, ovfl}
  393. state := newDecodeStateFromData(unsignedResult)
  394. execDec(instr, state, t, reflect.ValueOf(&data))
  395. if data != 17 {
  396. t.Errorf("uint32 a = %v not 17", data)
  397. }
  398. }
  399. // uintptr
  400. {
  401. var data uintptr
  402. instr := &decInstr{decOpTable[reflect.Uintptr], 6, nil, ovfl}
  403. state := newDecodeStateFromData(unsignedResult)
  404. execDec(instr, state, t, reflect.ValueOf(&data))
  405. if data != 17 {
  406. t.Errorf("uintptr a = %v not 17", data)
  407. }
  408. }
  409. // int64
  410. {
  411. var data int64
  412. instr := &decInstr{decInt64, 6, nil, ovfl}
  413. state := newDecodeStateFromData(signedResult)
  414. execDec(instr, state, t, reflect.ValueOf(&data))
  415. if data != 17 {
  416. t.Errorf("int64 a = %v not 17", data)
  417. }
  418. }
  419. // uint64
  420. {
  421. var data uint64
  422. instr := &decInstr{decUint64, 6, nil, ovfl}
  423. state := newDecodeStateFromData(unsignedResult)
  424. execDec(instr, state, t, reflect.ValueOf(&data))
  425. if data != 17 {
  426. t.Errorf("uint64 a = %v not 17", data)
  427. }
  428. }
  429. // float32
  430. {
  431. var data float32
  432. instr := &decInstr{decFloat32, 6, nil, ovfl}
  433. state := newDecodeStateFromData(floatResult)
  434. execDec(instr, state, t, reflect.ValueOf(&data))
  435. if data != 17 {
  436. t.Errorf("float32 a = %v not 17", data)
  437. }
  438. }
  439. // float64
  440. {
  441. var data float64
  442. instr := &decInstr{decFloat64, 6, nil, ovfl}
  443. state := newDecodeStateFromData(floatResult)
  444. execDec(instr, state, t, reflect.ValueOf(&data))
  445. if data != 17 {
  446. t.Errorf("float64 a = %v not 17", data)
  447. }
  448. }
  449. // complex64
  450. {
  451. var data complex64
  452. instr := &decInstr{decOpTable[reflect.Complex64], 6, nil, ovfl}
  453. state := newDecodeStateFromData(complexResult)
  454. execDec(instr, state, t, reflect.ValueOf(&data))
  455. if data != 17+19i {
  456. t.Errorf("complex a = %v not 17+19i", data)
  457. }
  458. }
  459. // complex128
  460. {
  461. var data complex128
  462. instr := &decInstr{decOpTable[reflect.Complex128], 6, nil, ovfl}
  463. state := newDecodeStateFromData(complexResult)
  464. execDec(instr, state, t, reflect.ValueOf(&data))
  465. if data != 17+19i {
  466. t.Errorf("complex a = %v not 17+19i", data)
  467. }
  468. }
  469. // bytes == []uint8
  470. {
  471. var data []byte
  472. instr := &decInstr{decUint8Slice, 6, nil, ovfl}
  473. state := newDecodeStateFromData(bytesResult)
  474. execDec(instr, state, t, reflect.ValueOf(&data))
  475. if string(data) != "hello" {
  476. t.Errorf(`bytes a = %q not "hello"`, string(data))
  477. }
  478. }
  479. // string
  480. {
  481. var data string
  482. instr := &decInstr{decString, 6, nil, ovfl}
  483. state := newDecodeStateFromData(bytesResult)
  484. execDec(instr, state, t, reflect.ValueOf(&data))
  485. if data != "hello" {
  486. t.Errorf(`bytes a = %q not "hello"`, data)
  487. }
  488. }
  489. }
  490. func TestEndToEnd(t *testing.T) {
  491. type T2 struct {
  492. T string
  493. }
  494. type T3 struct {
  495. X float64
  496. Z *int
  497. }
  498. type T1 struct {
  499. A, B, C int
  500. M map[string]*float64
  501. M2 map[int]T3
  502. Mstring map[string]string
  503. Mintptr map[int]*int
  504. Mcomp map[complex128]complex128
  505. Marr map[[2]string][2]*float64
  506. EmptyMap map[string]int // to check that we receive a non-nil map.
  507. N *[3]float64
  508. Strs *[2]string
  509. Int64s *[]int64
  510. RI complex64
  511. S string
  512. Y []byte
  513. T *T2
  514. }
  515. pi := 3.14159
  516. e := 2.71828
  517. two := 2.0
  518. meaning := 42
  519. fingers := 5
  520. s1 := "string1"
  521. s2 := "string2"
  522. var comp1 complex128 = complex(1.0, 1.0)
  523. var comp2 complex128 = complex(1.0, 1.0)
  524. var arr1 [2]string
  525. arr1[0] = s1
  526. arr1[1] = s2
  527. var arr2 [2]string
  528. arr2[0] = s2
  529. arr2[1] = s1
  530. var floatArr1 [2]*float64
  531. floatArr1[0] = &pi
  532. floatArr1[1] = &e
  533. var floatArr2 [2]*float64
  534. floatArr2[0] = &e
  535. floatArr2[1] = &two
  536. t1 := &T1{
  537. A: 17,
  538. B: 18,
  539. C: -5,
  540. M: map[string]*float64{"pi": &pi, "e": &e},
  541. M2: map[int]T3{4: {X: pi, Z: &meaning}, 10: {X: e, Z: &fingers}},
  542. Mstring: map[string]string{"pi": "3.14", "e": "2.71"},
  543. Mintptr: map[int]*int{meaning: &fingers, fingers: &meaning},
  544. Mcomp: map[complex128]complex128{comp1: comp2, comp2: comp1},
  545. Marr: map[[2]string][2]*float64{arr1: floatArr1, arr2: floatArr2},
  546. EmptyMap: make(map[string]int),
  547. N: &[3]float64{1.5, 2.5, 3.5},
  548. Strs: &[2]string{s1, s2},
  549. Int64s: &[]int64{77, 89, 123412342134},
  550. RI: 17 - 23i,
  551. S: "Now is the time",
  552. Y: []byte("hello, sailor"),
  553. T: &T2{"this is T2"},
  554. }
  555. b := new(bytes.Buffer)
  556. err := NewEncoder(b).Encode(t1)
  557. if err != nil {
  558. t.Error("encode:", err)
  559. }
  560. var _t1 T1
  561. err = NewDecoder(b).Decode(&_t1)
  562. if err != nil {
  563. t.Fatal("decode:", err)
  564. }
  565. if !reflect.DeepEqual(t1, &_t1) {
  566. t.Errorf("encode expected %v got %v", *t1, _t1)
  567. }
  568. // Be absolutely sure the received map is non-nil.
  569. if t1.EmptyMap == nil {
  570. t.Errorf("nil map sent")
  571. }
  572. if _t1.EmptyMap == nil {
  573. t.Errorf("nil map received")
  574. }
  575. }
  576. func TestOverflow(t *testing.T) {
  577. type inputT struct {
  578. Maxi int64
  579. Mini int64
  580. Maxu uint64
  581. Maxf float64
  582. Minf float64
  583. Maxc complex128
  584. Minc complex128
  585. }
  586. var it inputT
  587. var err error
  588. b := new(bytes.Buffer)
  589. enc := NewEncoder(b)
  590. dec := NewDecoder(b)
  591. // int8
  592. b.Reset()
  593. it = inputT{
  594. Maxi: math.MaxInt8 + 1,
  595. }
  596. type outi8 struct {
  597. Maxi int8
  598. Mini int8
  599. }
  600. var o1 outi8
  601. enc.Encode(it)
  602. err = dec.Decode(&o1)
  603. if err == nil || err.Error() != `value for "Maxi" out of range` {
  604. t.Error("wrong overflow error for int8:", err)
  605. }
  606. it = inputT{
  607. Mini: math.MinInt8 - 1,
  608. }
  609. b.Reset()
  610. enc.Encode(it)
  611. err = dec.Decode(&o1)
  612. if err == nil || err.Error() != `value for "Mini" out of range` {
  613. t.Error("wrong underflow error for int8:", err)
  614. }
  615. // int16
  616. b.Reset()
  617. it = inputT{
  618. Maxi: math.MaxInt16 + 1,
  619. }
  620. type outi16 struct {
  621. Maxi int16
  622. Mini int16
  623. }
  624. var o2 outi16
  625. enc.Encode(it)
  626. err = dec.Decode(&o2)
  627. if err == nil || err.Error() != `value for "Maxi" out of range` {
  628. t.Error("wrong overflow error for int16:", err)
  629. }
  630. it = inputT{
  631. Mini: math.MinInt16 - 1,
  632. }
  633. b.Reset()
  634. enc.Encode(it)
  635. err = dec.Decode(&o2)
  636. if err == nil || err.Error() != `value for "Mini" out of range` {
  637. t.Error("wrong underflow error for int16:", err)
  638. }
  639. // int32
  640. b.Reset()
  641. it = inputT{
  642. Maxi: math.MaxInt32 + 1,
  643. }
  644. type outi32 struct {
  645. Maxi int32
  646. Mini int32
  647. }
  648. var o3 outi32
  649. enc.Encode(it)
  650. err = dec.Decode(&o3)
  651. if err == nil || err.Error() != `value for "Maxi" out of range` {
  652. t.Error("wrong overflow error for int32:", err)
  653. }
  654. it = inputT{
  655. Mini: math.MinInt32 - 1,
  656. }
  657. b.Reset()
  658. enc.Encode(it)
  659. err = dec.Decode(&o3)
  660. if err == nil || err.Error() != `value for "Mini" out of range` {
  661. t.Error("wrong underflow error for int32:", err)
  662. }
  663. // uint8
  664. b.Reset()
  665. it = inputT{
  666. Maxu: math.MaxUint8 + 1,
  667. }
  668. type outu8 struct {
  669. Maxu uint8
  670. }
  671. var o4 outu8
  672. enc.Encode(it)
  673. err = dec.Decode(&o4)
  674. if err == nil || err.Error() != `value for "Maxu" out of range` {
  675. t.Error("wrong overflow error for uint8:", err)
  676. }
  677. // uint16
  678. b.Reset()
  679. it = inputT{
  680. Maxu: math.MaxUint16 + 1,
  681. }
  682. type outu16 struct {
  683. Maxu uint16
  684. }
  685. var o5 outu16
  686. enc.Encode(it)
  687. err = dec.Decode(&o5)
  688. if err == nil || err.Error() != `value for "Maxu" out of range` {
  689. t.Error("wrong overflow error for uint16:", err)
  690. }
  691. // uint32
  692. b.Reset()
  693. it = inputT{
  694. Maxu: math.MaxUint32 + 1,
  695. }
  696. type outu32 struct {
  697. Maxu uint32
  698. }
  699. var o6 outu32
  700. enc.Encode(it)
  701. err = dec.Decode(&o6)
  702. if err == nil || err.Error() != `value for "Maxu" out of range` {
  703. t.Error("wrong overflow error for uint32:", err)
  704. }
  705. // float32
  706. b.Reset()
  707. it = inputT{
  708. Maxf: math.MaxFloat32 * 2,
  709. }
  710. type outf32 struct {
  711. Maxf float32
  712. Minf float32
  713. }
  714. var o7 outf32
  715. enc.Encode(it)
  716. err = dec.Decode(&o7)
  717. if err == nil || err.Error() != `value for "Maxf" out of range` {
  718. t.Error("wrong overflow error for float32:", err)
  719. }
  720. // complex64
  721. b.Reset()
  722. it = inputT{
  723. Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2),
  724. }
  725. type outc64 struct {
  726. Maxc complex64
  727. Minc complex64
  728. }
  729. var o8 outc64
  730. enc.Encode(it)
  731. err = dec.Decode(&o8)
  732. if err == nil || err.Error() != `value for "Maxc" out of range` {
  733. t.Error("wrong overflow error for complex64:", err)
  734. }
  735. }
  736. func TestNesting(t *testing.T) {
  737. type RT struct {
  738. A string
  739. Next *RT
  740. }
  741. rt := new(RT)
  742. rt.A = "level1"
  743. rt.Next = new(RT)
  744. rt.Next.A = "level2"
  745. b := new(bytes.Buffer)
  746. NewEncoder(b).Encode(rt)
  747. var drt RT
  748. dec := NewDecoder(b)
  749. err := dec.Decode(&drt)
  750. if err != nil {
  751. t.Fatal("decoder error:", err)
  752. }
  753. if drt.A != rt.A {
  754. t.Errorf("nesting: encode expected %v got %v", *rt, drt)
  755. }
  756. if drt.Next == nil {
  757. t.Errorf("nesting: recursion failed")
  758. }
  759. if drt.Next.A != rt.Next.A {
  760. t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next)
  761. }
  762. }
  763. // These three structures have the same data with different indirections
  764. type T0 struct {
  765. A int
  766. B int
  767. C int
  768. D int
  769. }
  770. type T1 struct {
  771. A int
  772. B *int
  773. C **int
  774. D ***int
  775. }
  776. type T2 struct {
  777. A ***int
  778. B **int
  779. C *int
  780. D int
  781. }
  782. func TestAutoIndirection(t *testing.T) {
  783. // First transfer t1 into t0
  784. var t1 T1
  785. t1.A = 17
  786. t1.B = new(int)
  787. *t1.B = 177
  788. t1.C = new(*int)
  789. *t1.C = new(int)
  790. **t1.C = 1777
  791. t1.D = new(**int)
  792. *t1.D = new(*int)
  793. **t1.D = new(int)
  794. ***t1.D = 17777
  795. b := new(bytes.Buffer)
  796. enc := NewEncoder(b)
  797. enc.Encode(t1)
  798. dec := NewDecoder(b)
  799. var t0 T0
  800. dec.Decode(&t0)
  801. if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
  802. t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0)
  803. }
  804. // Now transfer t2 into t0
  805. var t2 T2
  806. t2.D = 17777
  807. t2.C = new(int)
  808. *t2.C = 1777
  809. t2.B = new(*int)
  810. *t2.B = new(int)
  811. **t2.B = 177
  812. t2.A = new(**int)
  813. *t2.A = new(*int)
  814. **t2.A = new(int)
  815. ***t2.A = 17
  816. b.Reset()
  817. enc.Encode(t2)
  818. t0 = T0{}
  819. dec.Decode(&t0)
  820. if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 {
  821. t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0)
  822. }
  823. // Now transfer t0 into t1
  824. t0 = T0{17, 177, 1777, 17777}
  825. b.Reset()
  826. enc.Encode(t0)
  827. t1 = T1{}
  828. dec.Decode(&t1)
  829. if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 {
  830. t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D)
  831. }
  832. // Now transfer t0 into t2
  833. b.Reset()
  834. enc.Encode(t0)
  835. t2 = T2{}
  836. dec.Decode(&t2)
  837. if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
  838. t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
  839. }
  840. // Now do t2 again but without pre-allocated pointers.
  841. b.Reset()
  842. enc.Encode(t0)
  843. ***t2.A = 0
  844. **t2.B = 0
  845. *t2.C = 0
  846. t2.D = 0
  847. dec.Decode(&t2)
  848. if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 {
  849. t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D)
  850. }
  851. }
  852. type RT0 struct {
  853. A int
  854. B string
  855. C float64
  856. }
  857. type RT1 struct {
  858. C float64
  859. B string
  860. A int
  861. NotSet string
  862. }
  863. func TestReorderedFields(t *testing.T) {
  864. var rt0 RT0
  865. rt0.A = 17
  866. rt0.B = "hello"
  867. rt0.C = 3.14159
  868. b := new(bytes.Buffer)
  869. NewEncoder(b).Encode(rt0)
  870. dec := NewDecoder(b)
  871. var rt1 RT1
  872. // Wire type is RT0, local type is RT1.
  873. err := dec.Decode(&rt1)
  874. if err != nil {
  875. t.Fatal("decode error:", err)
  876. }
  877. if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C {
  878. t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1)
  879. }
  880. }
  881. // Like an RT0 but with fields we'll ignore on the decode side.
  882. type IT0 struct {
  883. A int64
  884. B string
  885. Ignore_d []int
  886. Ignore_e [3]float64
  887. Ignore_f bool
  888. Ignore_g string
  889. Ignore_h []byte
  890. Ignore_i *RT1
  891. Ignore_m map[string]int
  892. C float64
  893. }
  894. func TestIgnoredFields(t *testing.T) {
  895. var it0 IT0
  896. it0.A = 17
  897. it0.B = "hello"
  898. it0.C = 3.14159
  899. it0.Ignore_d = []int{1, 2, 3}
  900. it0.Ignore_e[0] = 1.0
  901. it0.Ignore_e[1] = 2.0
  902. it0.Ignore_e[2] = 3.0
  903. it0.Ignore_f = true
  904. it0.Ignore_g = "pay no attention"
  905. it0.Ignore_h = []byte("to the curtain")
  906. it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"}
  907. it0.Ignore_m = map[string]int{"one": 1, "two": 2}
  908. b := new(bytes.Buffer)
  909. NewEncoder(b).Encode(it0)
  910. dec := NewDecoder(b)
  911. var rt1 RT1
  912. // Wire type is IT0, local type is RT1.
  913. err := dec.Decode(&rt1)
  914. if err != nil {
  915. t.Error("error: ", err)
  916. }
  917. if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C {
  918. t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1)
  919. }
  920. }
  921. func TestBadRecursiveType(t *testing.T) {
  922. type Rec ***Rec
  923. var rec Rec
  924. b := new(bytes.Buffer)
  925. err := NewEncoder(b).Encode(&rec)
  926. if err == nil {
  927. t.Error("expected error; got none")
  928. } else if !strings.Contains(err.Error(), "recursive") {
  929. t.Error("expected recursive type error; got", err)
  930. }
  931. // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder.
  932. }
  933. type Indirect struct {
  934. A ***[3]int
  935. S ***[]int
  936. M ****map[string]int
  937. }
  938. type Direct struct {
  939. A [3]int
  940. S []int
  941. M map[string]int
  942. }
  943. func TestIndirectSliceMapArray(t *testing.T) {
  944. // Marshal indirect, unmarshal to direct.
  945. i := new(Indirect)
  946. i.A = new(**[3]int)
  947. *i.A = new(*[3]int)
  948. **i.A = new([3]int)
  949. ***i.A = [3]int{1, 2, 3}
  950. i.S = new(**[]int)
  951. *i.S = new(*[]int)
  952. **i.S = new([]int)
  953. ***i.S = []int{4, 5, 6}
  954. i.M = new(***map[string]int)
  955. *i.M = new(**map[string]int)
  956. **i.M = new(*map[string]int)
  957. ***i.M = new(map[string]int)
  958. ****i.M = map[string]int{"one": 1, "two": 2, "three": 3}
  959. b := new(bytes.Buffer)
  960. NewEncoder(b).Encode(i)
  961. dec := NewDecoder(b)
  962. var d Direct
  963. err := dec.Decode(&d)
  964. if err != nil {
  965. t.Error("error: ", err)
  966. }
  967. if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 {
  968. t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A)
  969. }
  970. if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 {
  971. t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S)
  972. }
  973. if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 {
  974. t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M)
  975. }
  976. // Marshal direct, unmarshal to indirect.
  977. d.A = [3]int{11, 22, 33}
  978. d.S = []int{44, 55, 66}
  979. d.M = map[string]int{"four": 4, "five": 5, "six": 6}
  980. i = new(Indirect)
  981. b.Reset()
  982. NewEncoder(b).Encode(d)
  983. dec = NewDecoder(b)
  984. err = dec.Decode(&i)
  985. if err != nil {
  986. t.Fatal("error: ", err)
  987. }
  988. if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 {
  989. t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A)
  990. }
  991. if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 {
  992. t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S)
  993. }
  994. if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 {
  995. t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M)
  996. }
  997. }
  998. // An interface with several implementations
  999. type Squarer interface {
  1000. Square() int
  1001. }
  1002. type Int int
  1003. func (i Int) Square() int {
  1004. return int(i * i)
  1005. }
  1006. type Float float64
  1007. func (f Float) Square() int {
  1008. return int(f * f)
  1009. }
  1010. type Vector []int
  1011. func (v Vector) Square() int {
  1012. sum := 0
  1013. for _, x := range v {
  1014. sum += x * x
  1015. }
  1016. return sum
  1017. }
  1018. type Point struct {
  1019. X, Y int
  1020. }
  1021. func (p Point) Square() int {
  1022. return p.X*p.X + p.Y*p.Y
  1023. }
  1024. // A struct with interfaces in it.
  1025. type InterfaceItem struct {
  1026. I int
  1027. Sq1, Sq2, Sq3 Squarer
  1028. F float64
  1029. Sq []Squarer
  1030. }
  1031. // The same struct without interfaces
  1032. type NoInterfaceItem struct {
  1033. I int
  1034. F float64
  1035. }
  1036. func TestInterface(t *testing.T) {
  1037. iVal := Int(3)
  1038. fVal := Float(5)
  1039. // Sending a Vector will require that the receiver define a type in the middle of
  1040. // receiving the value for item2.
  1041. vVal := Vector{1, 2, 3}
  1042. b := new(bytes.Buffer)
  1043. item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}}
  1044. // Register the types.
  1045. Register(Int(0))
  1046. Register(Float(0))
  1047. Register(Vector{})
  1048. err := NewEncoder(b).Encode(item1)
  1049. if err != nil {
  1050. t.Error("expected no encode error; got", err)
  1051. }
  1052. item2 := InterfaceItem{}
  1053. err = NewDecoder(b).Decode(&item2)
  1054. if err != nil {
  1055. t.Fatal("decode:", err)
  1056. }
  1057. if item2.I != item1.I {
  1058. t.Error("normal int did not decode correctly")
  1059. }
  1060. if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() {
  1061. t.Error("Int did not decode correctly")
  1062. }
  1063. if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() {
  1064. t.Error("Float did not decode correctly")
  1065. }
  1066. if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() {
  1067. t.Error("Vector did not decode correctly")
  1068. }
  1069. if item2.F != item1.F {
  1070. t.Error("normal float did not decode correctly")
  1071. }
  1072. // Now check that we received a slice of Squarers correctly, including a nil element
  1073. if len(item1.Sq) != len(item2.Sq) {
  1074. t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq))
  1075. }
  1076. for i, v1 := range item1.Sq {
  1077. v2 := item2.Sq[i]
  1078. if v1 == nil || v2 == nil {
  1079. if v1 != nil || v2 != nil {
  1080. t.Errorf("item %d inconsistent nils", i)
  1081. }
  1082. } else if v1.Square() != v2.Square() {
  1083. t.Errorf("item %d inconsistent values: %v %v", i, v1, v2)
  1084. }
  1085. }
  1086. }
  1087. // A struct with all basic types, stored in interfaces.
  1088. type BasicInterfaceItem struct {
  1089. Int, Int8, Int16, Int32, Int64 any
  1090. Uint, Uint8, Uint16, Uint32, Uint64 any
  1091. Float32, Float64 any
  1092. Complex64, Complex128 any
  1093. Bool any
  1094. String any
  1095. Bytes any
  1096. }
  1097. func TestInterfaceBasic(t *testing.T) {
  1098. b := new(bytes.Buffer)
  1099. item1 := &BasicInterfaceItem{
  1100. int(1), int8(1), int16(1), int32(1), int64(1),
  1101. uint(1), uint8(1), uint16(1), uint32(1), uint64(1),
  1102. float32(1), 1.0,
  1103. complex64(1i), complex128(1i),
  1104. true,
  1105. "hello",
  1106. []byte("sailor"),
  1107. }
  1108. err := NewEncoder(b).Encode(item1)
  1109. if err != nil {
  1110. t.Error("expected no encode error; got", err)
  1111. }
  1112. item2 := &BasicInterfaceItem{}
  1113. err = NewDecoder(b).Decode(&item2)
  1114. if err != nil {
  1115. t.Fatal("decode:", err)
  1116. }
  1117. if !reflect.DeepEqual(item1, item2) {
  1118. t.Errorf("encode expected %v got %v", item1, item2)
  1119. }
  1120. // Hand check a couple for correct types.
  1121. if v, ok := item2.Bool.(bool); !ok || !v {
  1122. t.Error("boolean should be true")
  1123. }
  1124. if v, ok := item2.String.(string); !ok || v != item1.String.(string) {
  1125. t.Errorf("string should be %v is %v", item1.String, v)
  1126. }
  1127. }
  1128. type String string
  1129. type PtrInterfaceItem struct {
  1130. Str1 any // basic
  1131. Str2 any // derived
  1132. }
  1133. // We'll send pointers; should receive values.
  1134. // Also check that we can register T but send *T.
  1135. func TestInterfacePointer(t *testing.T) {
  1136. b := new(bytes.Buffer)
  1137. str1 := "howdy"
  1138. str2 := String("kiddo")
  1139. item1 := &PtrInterfaceItem{
  1140. &str1,
  1141. &str2,
  1142. }
  1143. // Register the type.
  1144. Register(str2)
  1145. err := NewEncoder(b).Encode(item1)
  1146. if err != nil {
  1147. t.Error("expected no encode error; got", err)
  1148. }
  1149. item2 := &PtrInterfaceItem{}
  1150. err = NewDecoder(b).Decode(&item2)
  1151. if err != nil {
  1152. t.Fatal("decode:", err)
  1153. }
  1154. // Hand test for correct types and values.
  1155. if v, ok := item2.Str1.(string); !ok || v != str1 {
  1156. t.Errorf("basic string failed: %q should be %q", v, str1)
  1157. }
  1158. if v, ok := item2.Str2.(String); !ok || v != str2 {
  1159. t.Errorf("derived type String failed: %q should be %q", v, str2)
  1160. }
  1161. }
  1162. func TestIgnoreInterface(t *testing.T) {
  1163. iVal := Int(3)
  1164. fVal := Float(5)
  1165. // Sending a Point will require that the receiver define a type in the middle of
  1166. // receiving the value for item2.
  1167. pVal := Point{2, 3}
  1168. b := new(bytes.Buffer)
  1169. item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil}
  1170. // Register the types.
  1171. Register(Int(0))
  1172. Register(Float(0))
  1173. Register(Point{})
  1174. err := NewEncoder(b).Encode(item1)
  1175. if err != nil {
  1176. t.Error("expected no encode error; got", err)
  1177. }
  1178. item2 := NoInterfaceItem{}
  1179. err = NewDecoder(b).Decode(&item2)
  1180. if err != nil {
  1181. t.Fatal("decode:", err)
  1182. }
  1183. if item2.I != item1.I {
  1184. t.Error("normal int did not decode correctly")
  1185. }
  1186. if item2.F != item1.F {
  1187. t.Error("normal float did not decode correctly")
  1188. }
  1189. }
  1190. type U struct {
  1191. A int
  1192. B string
  1193. c float64
  1194. D uint
  1195. }
  1196. func TestUnexportedFields(t *testing.T) {
  1197. var u0 U
  1198. u0.A = 17
  1199. u0.B = "hello"
  1200. u0.c = 3.14159
  1201. u0.D = 23
  1202. b := new(bytes.Buffer)
  1203. NewEncoder(b).Encode(u0)
  1204. dec := NewDecoder(b)
  1205. var u1 U
  1206. u1.c = 1234.
  1207. err := dec.Decode(&u1)
  1208. if err != nil {
  1209. t.Fatal("decode error:", err)
  1210. }
  1211. if u0.A != u1.A || u0.B != u1.B || u0.D != u1.D {
  1212. t.Errorf("u1->u0: expected %v; got %v", u0, u1)
  1213. }
  1214. if u1.c != 1234. {
  1215. t.Error("u1.c modified")
  1216. }
  1217. }
  1218. var singletons = []any{
  1219. true,
  1220. 7,
  1221. uint(10),
  1222. 3.2,
  1223. "hello",
  1224. [3]int{11, 22, 33},
  1225. []float32{0.5, 0.25, 0.125},
  1226. map[string]int{"one": 1, "two": 2},
  1227. }
  1228. func TestDebugSingleton(t *testing.T) {
  1229. if debugFunc == nil {
  1230. return
  1231. }
  1232. b := new(bytes.Buffer)
  1233. // Accumulate a number of values and print them out all at once.
  1234. for _, x := range singletons {
  1235. err := NewEncoder(b).Encode(x)
  1236. if err != nil {
  1237. t.Fatal("encode:", err)
  1238. }
  1239. }
  1240. debugFunc(b)
  1241. }
  1242. // A type that won't be defined in the gob until we send it in an interface value.
  1243. type OnTheFly struct {
  1244. A int
  1245. }
  1246. type DT struct {
  1247. // X OnTheFly
  1248. A int
  1249. B string
  1250. C float64
  1251. I any
  1252. J any
  1253. I_nil any
  1254. M map[string]int
  1255. T [3]int
  1256. S []string
  1257. }
  1258. func newDT() DT {
  1259. var dt DT
  1260. dt.A = 17
  1261. dt.B = "hello"
  1262. dt.C = 3.14159
  1263. dt.I = 271828
  1264. dt.J = OnTheFly{3}
  1265. dt.I_nil = nil
  1266. dt.M = map[string]int{"one": 1, "two": 2}
  1267. dt.T = [3]int{11, 22, 33}
  1268. dt.S = []string{"hi", "joe"}
  1269. return dt
  1270. }
  1271. func TestDebugStruct(t *testing.T) {
  1272. if debugFunc == nil {
  1273. return
  1274. }
  1275. Register(OnTheFly{})
  1276. dt := newDT()
  1277. b := new(bytes.Buffer)
  1278. err := NewEncoder(b).Encode(dt)
  1279. if err != nil {
  1280. t.Fatal("encode:", err)
  1281. }
  1282. debugBuffer := bytes.NewBuffer(b.Bytes())
  1283. dt2 := &DT{}
  1284. err = NewDecoder(b).Decode(&dt2)
  1285. if err != nil {
  1286. t.Error("decode:", err)
  1287. }
  1288. debugFunc(debugBuffer)
  1289. }
  1290. func encFuzzDec(rng *rand.Rand, in any) error {
  1291. buf := new(bytes.Buffer)
  1292. enc := NewEncoder(buf)
  1293. if err := enc.Encode(&in); err != nil {
  1294. return err
  1295. }
  1296. b := buf.Bytes()
  1297. for i, bi := range b {
  1298. if rng.Intn(10) < 3 {
  1299. b[i] = bi + uint8(rng.Intn(256))
  1300. }
  1301. }
  1302. dec := NewDecoder(buf)
  1303. var e any
  1304. if err := dec.Decode(&e); err != nil {
  1305. return err
  1306. }
  1307. return nil
  1308. }
  1309. // This does some "fuzz testing" by attempting to decode a sequence of random bytes.
  1310. func TestFuzz(t *testing.T) {
  1311. if !*doFuzzTests {
  1312. t.Skipf("disabled; run with -gob.fuzz to enable")
  1313. }
  1314. // all possible inputs
  1315. input := []any{
  1316. new(int),
  1317. new(float32),
  1318. new(float64),
  1319. new(complex128),
  1320. &ByteStruct{255},
  1321. &ArrayStruct{},
  1322. &StringStruct{"hello"},
  1323. &GobTest1{0, &StringStruct{"hello"}},
  1324. }
  1325. testFuzz(t, time.Now().UnixNano(), 100, input...)
  1326. }
  1327. func TestFuzzRegressions(t *testing.T) {
  1328. if !*doFuzzTests {
  1329. t.Skipf("disabled; run with -gob.fuzz to enable")
  1330. }
  1331. // An instance triggering a type name of length ~102 GB.
  1332. testFuzz(t, 1328492090837718000, 100, new(float32))
  1333. // An instance triggering a type name of 1.6 GB.
  1334. // Note: can take several minutes to run.
  1335. testFuzz(t, 1330522872628565000, 100, new(int))
  1336. }
  1337. func testFuzz(t *testing.T, seed int64, n int, input ...any) {
  1338. for _, e := range input {
  1339. t.Logf("seed=%d n=%d e=%T", seed, n, e)
  1340. rng := rand.New(rand.NewSource(seed))
  1341. for i := 0; i < n; i++ {
  1342. encFuzzDec(rng, e)
  1343. }
  1344. }
  1345. }
  1346. // TestFuzzOneByte tries to decode corrupted input sequences
  1347. // and checks that no panic occurs.
  1348. func TestFuzzOneByte(t *testing.T) {
  1349. if !*doFuzzTests {
  1350. t.Skipf("disabled; run with -gob.fuzz to enable")
  1351. }
  1352. buf := new(bytes.Buffer)
  1353. Register(OnTheFly{})
  1354. dt := newDT()
  1355. if err := NewEncoder(buf).Encode(dt); err != nil {
  1356. t.Fatal(err)
  1357. }
  1358. s := buf.String()
  1359. indices := make([]int, 0, len(s))
  1360. for i := 0; i < len(s); i++ {
  1361. switch i {
  1362. case 14, 167, 231, 265: // a slice length, corruptions are not handled yet.
  1363. continue
  1364. case 248:
  1365. // Large map size, which currently causes an out of memory panic.
  1366. // See golang.org/issue/24308 and golang.org/issue/20221.
  1367. continue
  1368. }
  1369. indices = append(indices, i)
  1370. }
  1371. if testing.Short() {
  1372. indices = []int{1, 111, 178} // known fixed panics
  1373. }
  1374. for _, i := range indices {
  1375. for j := 0; j < 256; j += 3 {
  1376. b := []byte(s)
  1377. b[i] ^= byte(j)
  1378. var e DT
  1379. func() {
  1380. defer func() {
  1381. if p := recover(); p != nil {
  1382. t.Errorf("crash for b[%d] ^= 0x%x", i, j)
  1383. panic(p)
  1384. }
  1385. }()
  1386. err := NewDecoder(bytes.NewReader(b)).Decode(&e)
  1387. _ = err
  1388. }()
  1389. }
  1390. }
  1391. }
  1392. // Don't crash, just give error with invalid type id.
  1393. // Issue 9649.
  1394. func TestErrorInvalidTypeId(t *testing.T) {
  1395. data := []byte{0x01, 0x00, 0x01, 0x00}
  1396. d := NewDecoder(bytes.NewReader(data))
  1397. // When running d.Decode(&foo) the first time the decoder stops
  1398. // after []byte{0x01, 0x00} and reports an errBadType. Running
  1399. // d.Decode(&foo) again on exactly the same input sequence should
  1400. // give another errBadType, but instead caused a panic because
  1401. // decoderMap wasn't cleaned up properly after the first error.
  1402. for i := 0; i < 2; i++ {
  1403. var foo struct{}
  1404. err := d.Decode(&foo)
  1405. if err != errBadType {
  1406. t.Fatalf("decode: expected %s, got %s", errBadType, err)
  1407. }
  1408. }
  1409. }