OSDN Git Service

versoin1.1.9 (#594)
[bytom/vapor.git] / vendor / github.com / golang / protobuf / proto / all_test.go
1 // Go support for Protocol Buffers - Google's data interchange format
2 //
3 // Copyright 2010 The Go Authors.  All rights reserved.
4 // https://github.com/golang/protobuf
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
8 // met:
9 //
10 //     * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 //     * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
15 // distribution.
16 //     * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31
32 package proto_test
33
34 import (
35         "bytes"
36         "encoding/json"
37         "errors"
38         "fmt"
39         "math"
40         "math/rand"
41         "reflect"
42         "runtime/debug"
43         "strings"
44         "testing"
45         "time"
46
47         . "github.com/golang/protobuf/proto"
48         . "github.com/golang/protobuf/proto/testdata"
49 )
50
51 var globalO *Buffer
52
53 func old() *Buffer {
54         if globalO == nil {
55                 globalO = NewBuffer(nil)
56         }
57         globalO.Reset()
58         return globalO
59 }
60
61 func equalbytes(b1, b2 []byte, t *testing.T) {
62         if len(b1) != len(b2) {
63                 t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2))
64                 return
65         }
66         for i := 0; i < len(b1); i++ {
67                 if b1[i] != b2[i] {
68                         t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
69                 }
70         }
71 }
72
73 func initGoTestField() *GoTestField {
74         f := new(GoTestField)
75         f.Label = String("label")
76         f.Type = String("type")
77         return f
78 }
79
80 // These are all structurally equivalent but the tag numbers differ.
81 // (It's remarkable that required, optional, and repeated all have
82 // 8 letters.)
83 func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
84         return &GoTest_RequiredGroup{
85                 RequiredField: String("required"),
86         }
87 }
88
89 func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
90         return &GoTest_OptionalGroup{
91                 RequiredField: String("optional"),
92         }
93 }
94
95 func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
96         return &GoTest_RepeatedGroup{
97                 RequiredField: String("repeated"),
98         }
99 }
100
101 func initGoTest(setdefaults bool) *GoTest {
102         pb := new(GoTest)
103         if setdefaults {
104                 pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
105                 pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
106                 pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
107                 pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
108                 pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
109                 pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
110                 pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
111                 pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
112                 pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
113                 pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
114                 pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
115                 pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
116                 pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
117         }
118
119         pb.Kind = GoTest_TIME.Enum()
120         pb.RequiredField = initGoTestField()
121         pb.F_BoolRequired = Bool(true)
122         pb.F_Int32Required = Int32(3)
123         pb.F_Int64Required = Int64(6)
124         pb.F_Fixed32Required = Uint32(32)
125         pb.F_Fixed64Required = Uint64(64)
126         pb.F_Uint32Required = Uint32(3232)
127         pb.F_Uint64Required = Uint64(6464)
128         pb.F_FloatRequired = Float32(3232)
129         pb.F_DoubleRequired = Float64(6464)
130         pb.F_StringRequired = String("string")
131         pb.F_BytesRequired = []byte("bytes")
132         pb.F_Sint32Required = Int32(-32)
133         pb.F_Sint64Required = Int64(-64)
134         pb.Requiredgroup = initGoTest_RequiredGroup()
135
136         return pb
137 }
138
139 func fail(msg string, b *bytes.Buffer, s string, t *testing.T) {
140         data := b.Bytes()
141         ld := len(data)
142         ls := len(s) / 2
143
144         fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls)
145
146         // find the interesting spot - n
147         n := ls
148         if ld < ls {
149                 n = ld
150         }
151         j := 0
152         for i := 0; i < n; i++ {
153                 bs := hex(s[j])*16 + hex(s[j+1])
154                 j += 2
155                 if data[i] == bs {
156                         continue
157                 }
158                 n = i
159                 break
160         }
161         l := n - 10
162         if l < 0 {
163                 l = 0
164         }
165         h := n + 10
166
167         // find the interesting spot - n
168         fmt.Printf("is[%d]:", l)
169         for i := l; i < h; i++ {
170                 if i >= ld {
171                         fmt.Printf(" --")
172                         continue
173                 }
174                 fmt.Printf(" %.2x", data[i])
175         }
176         fmt.Printf("\n")
177
178         fmt.Printf("sb[%d]:", l)
179         for i := l; i < h; i++ {
180                 if i >= ls {
181                         fmt.Printf(" --")
182                         continue
183                 }
184                 bs := hex(s[j])*16 + hex(s[j+1])
185                 j += 2
186                 fmt.Printf(" %.2x", bs)
187         }
188         fmt.Printf("\n")
189
190         t.Fail()
191
192         //      t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes())
193         // Print the output in a partially-decoded format; can
194         // be helpful when updating the test.  It produces the output
195         // that is pasted, with minor edits, into the argument to verify().
196         //      data := b.Bytes()
197         //      nesting := 0
198         //      for b.Len() > 0 {
199         //              start := len(data) - b.Len()
200         //              var u uint64
201         //              u, err := DecodeVarint(b)
202         //              if err != nil {
203         //                      fmt.Printf("decode error on varint:", err)
204         //                      return
205         //              }
206         //              wire := u & 0x7
207         //              tag := u >> 3
208         //              switch wire {
209         //              case WireVarint:
210         //                      v, err := DecodeVarint(b)
211         //                      if err != nil {
212         //                              fmt.Printf("decode error on varint:", err)
213         //                              return
214         //                      }
215         //                      fmt.Printf("\t\t\"%x\"  // field %d, encoding %d, value %d\n",
216         //                              data[start:len(data)-b.Len()], tag, wire, v)
217         //              case WireFixed32:
218         //                      v, err := DecodeFixed32(b)
219         //                      if err != nil {
220         //                              fmt.Printf("decode error on fixed32:", err)
221         //                              return
222         //                      }
223         //                      fmt.Printf("\t\t\"%x\"  // field %d, encoding %d, value %d\n",
224         //                              data[start:len(data)-b.Len()], tag, wire, v)
225         //              case WireFixed64:
226         //                      v, err := DecodeFixed64(b)
227         //                      if err != nil {
228         //                              fmt.Printf("decode error on fixed64:", err)
229         //                              return
230         //                      }
231         //                      fmt.Printf("\t\t\"%x\"  // field %d, encoding %d, value %d\n",
232         //                              data[start:len(data)-b.Len()], tag, wire, v)
233         //              case WireBytes:
234         //                      nb, err := DecodeVarint(b)
235         //                      if err != nil {
236         //                              fmt.Printf("decode error on bytes:", err)
237         //                              return
238         //                      }
239         //                      after_tag := len(data) - b.Len()
240         //                      str := make([]byte, nb)
241         //                      _, err = b.Read(str)
242         //                      if err != nil {
243         //                              fmt.Printf("decode error on bytes:", err)
244         //                              return
245         //                      }
246         //                      fmt.Printf("\t\t\"%x\" \"%x\"  // field %d, encoding %d (FIELD)\n",
247         //                              data[start:after_tag], str, tag, wire)
248         //              case WireStartGroup:
249         //                      nesting++
250         //                      fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n",
251         //                              data[start:len(data)-b.Len()], tag, nesting)
252         //              case WireEndGroup:
253         //                      fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n",
254         //                              data[start:len(data)-b.Len()], tag, nesting)
255         //                      nesting--
256         //              default:
257         //                      fmt.Printf("unrecognized wire type %d\n", wire)
258         //                      return
259         //              }
260         //      }
261 }
262
263 func hex(c uint8) uint8 {
264         if '0' <= c && c <= '9' {
265                 return c - '0'
266         }
267         if 'a' <= c && c <= 'f' {
268                 return 10 + c - 'a'
269         }
270         if 'A' <= c && c <= 'F' {
271                 return 10 + c - 'A'
272         }
273         return 0
274 }
275
276 func equal(b []byte, s string, t *testing.T) bool {
277         if 2*len(b) != len(s) {
278                 //              fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t)
279                 fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s))
280                 return false
281         }
282         for i, j := 0, 0; i < len(b); i, j = i+1, j+2 {
283                 x := hex(s[j])*16 + hex(s[j+1])
284                 if b[i] != x {
285                         //                      fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t)
286                         fmt.Printf("bad byte[%d]:%x %x", i, b[i], x)
287                         return false
288                 }
289         }
290         return true
291 }
292
293 func overify(t *testing.T, pb *GoTest, expected string) {
294         o := old()
295         err := o.Marshal(pb)
296         if err != nil {
297                 fmt.Printf("overify marshal-1 err = %v", err)
298                 o.DebugPrint("", o.Bytes())
299                 t.Fatalf("expected = %s", expected)
300         }
301         if !equal(o.Bytes(), expected, t) {
302                 o.DebugPrint("overify neq 1", o.Bytes())
303                 t.Fatalf("expected = %s", expected)
304         }
305
306         // Now test Unmarshal by recreating the original buffer.
307         pbd := new(GoTest)
308         err = o.Unmarshal(pbd)
309         if err != nil {
310                 t.Fatalf("overify unmarshal err = %v", err)
311                 o.DebugPrint("", o.Bytes())
312                 t.Fatalf("string = %s", expected)
313         }
314         o.Reset()
315         err = o.Marshal(pbd)
316         if err != nil {
317                 t.Errorf("overify marshal-2 err = %v", err)
318                 o.DebugPrint("", o.Bytes())
319                 t.Fatalf("string = %s", expected)
320         }
321         if !equal(o.Bytes(), expected, t) {
322                 o.DebugPrint("overify neq 2", o.Bytes())
323                 t.Fatalf("string = %s", expected)
324         }
325 }
326
327 // Simple tests for numeric encode/decode primitives (varint, etc.)
328 func TestNumericPrimitives(t *testing.T) {
329         for i := uint64(0); i < 1e6; i += 111 {
330                 o := old()
331                 if o.EncodeVarint(i) != nil {
332                         t.Error("EncodeVarint")
333                         break
334                 }
335                 x, e := o.DecodeVarint()
336                 if e != nil {
337                         t.Fatal("DecodeVarint")
338                 }
339                 if x != i {
340                         t.Fatal("varint decode fail:", i, x)
341                 }
342
343                 o = old()
344                 if o.EncodeFixed32(i) != nil {
345                         t.Fatal("encFixed32")
346                 }
347                 x, e = o.DecodeFixed32()
348                 if e != nil {
349                         t.Fatal("decFixed32")
350                 }
351                 if x != i {
352                         t.Fatal("fixed32 decode fail:", i, x)
353                 }
354
355                 o = old()
356                 if o.EncodeFixed64(i*1234567) != nil {
357                         t.Error("encFixed64")
358                         break
359                 }
360                 x, e = o.DecodeFixed64()
361                 if e != nil {
362                         t.Error("decFixed64")
363                         break
364                 }
365                 if x != i*1234567 {
366                         t.Error("fixed64 decode fail:", i*1234567, x)
367                         break
368                 }
369
370                 o = old()
371                 i32 := int32(i - 12345)
372                 if o.EncodeZigzag32(uint64(i32)) != nil {
373                         t.Fatal("EncodeZigzag32")
374                 }
375                 x, e = o.DecodeZigzag32()
376                 if e != nil {
377                         t.Fatal("DecodeZigzag32")
378                 }
379                 if x != uint64(uint32(i32)) {
380                         t.Fatal("zigzag32 decode fail:", i32, x)
381                 }
382
383                 o = old()
384                 i64 := int64(i - 12345)
385                 if o.EncodeZigzag64(uint64(i64)) != nil {
386                         t.Fatal("EncodeZigzag64")
387                 }
388                 x, e = o.DecodeZigzag64()
389                 if e != nil {
390                         t.Fatal("DecodeZigzag64")
391                 }
392                 if x != uint64(i64) {
393                         t.Fatal("zigzag64 decode fail:", i64, x)
394                 }
395         }
396 }
397
398 // fakeMarshaler is a simple struct implementing Marshaler and Message interfaces.
399 type fakeMarshaler struct {
400         b   []byte
401         err error
402 }
403
404 func (f *fakeMarshaler) Marshal() ([]byte, error) { return f.b, f.err }
405 func (f *fakeMarshaler) String() string           { return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err) }
406 func (f *fakeMarshaler) ProtoMessage()            {}
407 func (f *fakeMarshaler) Reset()                   {}
408
409 type msgWithFakeMarshaler struct {
410         M *fakeMarshaler `protobuf:"bytes,1,opt,name=fake"`
411 }
412
413 func (m *msgWithFakeMarshaler) String() string { return CompactTextString(m) }
414 func (m *msgWithFakeMarshaler) ProtoMessage()  {}
415 func (m *msgWithFakeMarshaler) Reset()         {}
416
417 // Simple tests for proto messages that implement the Marshaler interface.
418 func TestMarshalerEncoding(t *testing.T) {
419         tests := []struct {
420                 name    string
421                 m       Message
422                 want    []byte
423                 errType reflect.Type
424         }{
425                 {
426                         name: "Marshaler that fails",
427                         m: &fakeMarshaler{
428                                 err: errors.New("some marshal err"),
429                                 b:   []byte{5, 6, 7},
430                         },
431                         // Since the Marshal method returned bytes, they should be written to the
432                         // buffer.  (For efficiency, we assume that Marshal implementations are
433                         // always correct w.r.t. RequiredNotSetError and output.)
434                         want:    []byte{5, 6, 7},
435                         errType: reflect.TypeOf(errors.New("some marshal err")),
436                 },
437                 {
438                         name: "Marshaler that fails with RequiredNotSetError",
439                         m: &msgWithFakeMarshaler{
440                                 M: &fakeMarshaler{
441                                         err: &RequiredNotSetError{},
442                                         b:   []byte{5, 6, 7},
443                                 },
444                         },
445                         // Since there's an error that can be continued after,
446                         // the buffer should be written.
447                         want: []byte{
448                                 10, 3, // for &msgWithFakeMarshaler
449                                 5, 6, 7, // for &fakeMarshaler
450                         },
451                         errType: reflect.TypeOf(&RequiredNotSetError{}),
452                 },
453                 {
454                         name: "Marshaler that succeeds",
455                         m: &fakeMarshaler{
456                                 b: []byte{0, 1, 2, 3, 4, 127, 255},
457                         },
458                         want: []byte{0, 1, 2, 3, 4, 127, 255},
459                 },
460         }
461         for _, test := range tests {
462                 b := NewBuffer(nil)
463                 err := b.Marshal(test.m)
464                 if reflect.TypeOf(err) != test.errType {
465                         t.Errorf("%s: got err %T(%v) wanted %T", test.name, err, err, test.errType)
466                 }
467                 if !reflect.DeepEqual(test.want, b.Bytes()) {
468                         t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want)
469                 }
470                 if size := Size(test.m); size != len(b.Bytes()) {
471                         t.Errorf("%s: Size(_) = %v, but marshaled to %v bytes", test.name, size, len(b.Bytes()))
472                 }
473
474                 m, mErr := Marshal(test.m)
475                 if !bytes.Equal(b.Bytes(), m) {
476                         t.Errorf("%s: Marshal returned %v, but (*Buffer).Marshal wrote %v", test.name, m, b.Bytes())
477                 }
478                 if !reflect.DeepEqual(err, mErr) {
479                         t.Errorf("%s: Marshal err = %q, but (*Buffer).Marshal returned %q",
480                                 test.name, fmt.Sprint(mErr), fmt.Sprint(err))
481                 }
482         }
483 }
484
485 // Simple tests for bytes
486 func TestBytesPrimitives(t *testing.T) {
487         o := old()
488         bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
489         if o.EncodeRawBytes(bytes) != nil {
490                 t.Error("EncodeRawBytes")
491         }
492         decb, e := o.DecodeRawBytes(false)
493         if e != nil {
494                 t.Error("DecodeRawBytes")
495         }
496         equalbytes(bytes, decb, t)
497 }
498
499 // Simple tests for strings
500 func TestStringPrimitives(t *testing.T) {
501         o := old()
502         s := "now is the time"
503         if o.EncodeStringBytes(s) != nil {
504                 t.Error("enc_string")
505         }
506         decs, e := o.DecodeStringBytes()
507         if e != nil {
508                 t.Error("dec_string")
509         }
510         if s != decs {
511                 t.Error("string encode/decode fail:", s, decs)
512         }
513 }
514
515 // Do we catch the "required bit not set" case?
516 func TestRequiredBit(t *testing.T) {
517         o := old()
518         pb := new(GoTest)
519         err := o.Marshal(pb)
520         if err == nil {
521                 t.Error("did not catch missing required fields")
522         } else if strings.Index(err.Error(), "Kind") < 0 {
523                 t.Error("wrong error type:", err)
524         }
525 }
526
527 // Check that all fields are nil.
528 // Clearly silly, and a residue from a more interesting test with an earlier,
529 // different initialization property, but it once caught a compiler bug so
530 // it lives.
531 func checkInitialized(pb *GoTest, t *testing.T) {
532         if pb.F_BoolDefaulted != nil {
533                 t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
534         }
535         if pb.F_Int32Defaulted != nil {
536                 t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
537         }
538         if pb.F_Int64Defaulted != nil {
539                 t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
540         }
541         if pb.F_Fixed32Defaulted != nil {
542                 t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
543         }
544         if pb.F_Fixed64Defaulted != nil {
545                 t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
546         }
547         if pb.F_Uint32Defaulted != nil {
548                 t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
549         }
550         if pb.F_Uint64Defaulted != nil {
551                 t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
552         }
553         if pb.F_FloatDefaulted != nil {
554                 t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
555         }
556         if pb.F_DoubleDefaulted != nil {
557                 t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
558         }
559         if pb.F_StringDefaulted != nil {
560                 t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
561         }
562         if pb.F_BytesDefaulted != nil {
563                 t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
564         }
565         if pb.F_Sint32Defaulted != nil {
566                 t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
567         }
568         if pb.F_Sint64Defaulted != nil {
569                 t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
570         }
571 }
572
573 // Does Reset() reset?
574 func TestReset(t *testing.T) {
575         pb := initGoTest(true)
576         // muck with some values
577         pb.F_BoolDefaulted = Bool(false)
578         pb.F_Int32Defaulted = Int32(237)
579         pb.F_Int64Defaulted = Int64(12346)
580         pb.F_Fixed32Defaulted = Uint32(32000)
581         pb.F_Fixed64Defaulted = Uint64(666)
582         pb.F_Uint32Defaulted = Uint32(323232)
583         pb.F_Uint64Defaulted = nil
584         pb.F_FloatDefaulted = nil
585         pb.F_DoubleDefaulted = Float64(0)
586         pb.F_StringDefaulted = String("gotcha")
587         pb.F_BytesDefaulted = []byte("asdfasdf")
588         pb.F_Sint32Defaulted = Int32(123)
589         pb.F_Sint64Defaulted = Int64(789)
590         pb.Reset()
591         checkInitialized(pb, t)
592 }
593
594 // All required fields set, no defaults provided.
595 func TestEncodeDecode1(t *testing.T) {
596         pb := initGoTest(false)
597         overify(t, pb,
598                 "0807"+ // field 1, encoding 0, value 7
599                         "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
600                         "5001"+ // field 10, encoding 0, value 1
601                         "5803"+ // field 11, encoding 0, value 3
602                         "6006"+ // field 12, encoding 0, value 6
603                         "6d20000000"+ // field 13, encoding 5, value 0x20
604                         "714000000000000000"+ // field 14, encoding 1, value 0x40
605                         "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
606                         "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
607                         "8d0100004a45"+ // field 17, encoding 5, value 3232.0
608                         "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
609                         "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
610                         "b304"+ // field 70, encoding 3, start group
611                         "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
612                         "b404"+ // field 70, encoding 4, end group
613                         "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
614                         "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
615                         "b8067f") // field 103, encoding 0, 0x7f zigzag64
616 }
617
618 // All required fields set, defaults provided.
619 func TestEncodeDecode2(t *testing.T) {
620         pb := initGoTest(true)
621         overify(t, pb,
622                 "0807"+ // field 1, encoding 0, value 7
623                         "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
624                         "5001"+ // field 10, encoding 0, value 1
625                         "5803"+ // field 11, encoding 0, value 3
626                         "6006"+ // field 12, encoding 0, value 6
627                         "6d20000000"+ // field 13, encoding 5, value 32
628                         "714000000000000000"+ // field 14, encoding 1, value 64
629                         "78a019"+ // field 15, encoding 0, value 3232
630                         "8001c032"+ // field 16, encoding 0, value 6464
631                         "8d0100004a45"+ // field 17, encoding 5, value 3232.0
632                         "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
633                         "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
634                         "c00201"+ // field 40, encoding 0, value 1
635                         "c80220"+ // field 41, encoding 0, value 32
636                         "d00240"+ // field 42, encoding 0, value 64
637                         "dd0240010000"+ // field 43, encoding 5, value 320
638                         "e1028002000000000000"+ // field 44, encoding 1, value 640
639                         "e8028019"+ // field 45, encoding 0, value 3200
640                         "f0028032"+ // field 46, encoding 0, value 6400
641                         "fd02e0659948"+ // field 47, encoding 5, value 314159.0
642                         "81030000000050971041"+ // field 48, encoding 1, value 271828.0
643                         "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
644                         "b304"+ // start group field 70 level 1
645                         "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
646                         "b404"+ // end group field 70 level 1
647                         "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
648                         "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
649                         "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
650                         "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
651                         "90193f"+ // field 402, encoding 0, value 63
652                         "98197f") // field 403, encoding 0, value 127
653
654 }
655
656 // All default fields set to their default value by hand
657 func TestEncodeDecode3(t *testing.T) {
658         pb := initGoTest(false)
659         pb.F_BoolDefaulted = Bool(true)
660         pb.F_Int32Defaulted = Int32(32)
661         pb.F_Int64Defaulted = Int64(64)
662         pb.F_Fixed32Defaulted = Uint32(320)
663         pb.F_Fixed64Defaulted = Uint64(640)
664         pb.F_Uint32Defaulted = Uint32(3200)
665         pb.F_Uint64Defaulted = Uint64(6400)
666         pb.F_FloatDefaulted = Float32(314159)
667         pb.F_DoubleDefaulted = Float64(271828)
668         pb.F_StringDefaulted = String("hello, \"world!\"\n")
669         pb.F_BytesDefaulted = []byte("Bignose")
670         pb.F_Sint32Defaulted = Int32(-32)
671         pb.F_Sint64Defaulted = Int64(-64)
672
673         overify(t, pb,
674                 "0807"+ // field 1, encoding 0, value 7
675                         "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
676                         "5001"+ // field 10, encoding 0, value 1
677                         "5803"+ // field 11, encoding 0, value 3
678                         "6006"+ // field 12, encoding 0, value 6
679                         "6d20000000"+ // field 13, encoding 5, value 32
680                         "714000000000000000"+ // field 14, encoding 1, value 64
681                         "78a019"+ // field 15, encoding 0, value 3232
682                         "8001c032"+ // field 16, encoding 0, value 6464
683                         "8d0100004a45"+ // field 17, encoding 5, value 3232.0
684                         "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
685                         "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
686                         "c00201"+ // field 40, encoding 0, value 1
687                         "c80220"+ // field 41, encoding 0, value 32
688                         "d00240"+ // field 42, encoding 0, value 64
689                         "dd0240010000"+ // field 43, encoding 5, value 320
690                         "e1028002000000000000"+ // field 44, encoding 1, value 640
691                         "e8028019"+ // field 45, encoding 0, value 3200
692                         "f0028032"+ // field 46, encoding 0, value 6400
693                         "fd02e0659948"+ // field 47, encoding 5, value 314159.0
694                         "81030000000050971041"+ // field 48, encoding 1, value 271828.0
695                         "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
696                         "b304"+ // start group field 70 level 1
697                         "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
698                         "b404"+ // end group field 70 level 1
699                         "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
700                         "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
701                         "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
702                         "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
703                         "90193f"+ // field 402, encoding 0, value 63
704                         "98197f") // field 403, encoding 0, value 127
705
706 }
707
708 // All required fields set, defaults provided, all non-defaulted optional fields have values.
709 func TestEncodeDecode4(t *testing.T) {
710         pb := initGoTest(true)
711         pb.Table = String("hello")
712         pb.Param = Int32(7)
713         pb.OptionalField = initGoTestField()
714         pb.F_BoolOptional = Bool(true)
715         pb.F_Int32Optional = Int32(32)
716         pb.F_Int64Optional = Int64(64)
717         pb.F_Fixed32Optional = Uint32(3232)
718         pb.F_Fixed64Optional = Uint64(6464)
719         pb.F_Uint32Optional = Uint32(323232)
720         pb.F_Uint64Optional = Uint64(646464)
721         pb.F_FloatOptional = Float32(32.)
722         pb.F_DoubleOptional = Float64(64.)
723         pb.F_StringOptional = String("hello")
724         pb.F_BytesOptional = []byte("Bignose")
725         pb.F_Sint32Optional = Int32(-32)
726         pb.F_Sint64Optional = Int64(-64)
727         pb.Optionalgroup = initGoTest_OptionalGroup()
728
729         overify(t, pb,
730                 "0807"+ // field 1, encoding 0, value 7
731                         "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
732                         "1807"+ // field 3, encoding 0, value 7
733                         "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
734                         "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
735                         "5001"+ // field 10, encoding 0, value 1
736                         "5803"+ // field 11, encoding 0, value 3
737                         "6006"+ // field 12, encoding 0, value 6
738                         "6d20000000"+ // field 13, encoding 5, value 32
739                         "714000000000000000"+ // field 14, encoding 1, value 64
740                         "78a019"+ // field 15, encoding 0, value 3232
741                         "8001c032"+ // field 16, encoding 0, value 6464
742                         "8d0100004a45"+ // field 17, encoding 5, value 3232.0
743                         "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
744                         "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
745                         "f00101"+ // field 30, encoding 0, value 1
746                         "f80120"+ // field 31, encoding 0, value 32
747                         "800240"+ // field 32, encoding 0, value 64
748                         "8d02a00c0000"+ // field 33, encoding 5, value 3232
749                         "91024019000000000000"+ // field 34, encoding 1, value 6464
750                         "9802a0dd13"+ // field 35, encoding 0, value 323232
751                         "a002c0ba27"+ // field 36, encoding 0, value 646464
752                         "ad0200000042"+ // field 37, encoding 5, value 32.0
753                         "b1020000000000005040"+ // field 38, encoding 1, value 64.0
754                         "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
755                         "c00201"+ // field 40, encoding 0, value 1
756                         "c80220"+ // field 41, encoding 0, value 32
757                         "d00240"+ // field 42, encoding 0, value 64
758                         "dd0240010000"+ // field 43, encoding 5, value 320
759                         "e1028002000000000000"+ // field 44, encoding 1, value 640
760                         "e8028019"+ // field 45, encoding 0, value 3200
761                         "f0028032"+ // field 46, encoding 0, value 6400
762                         "fd02e0659948"+ // field 47, encoding 5, value 314159.0
763                         "81030000000050971041"+ // field 48, encoding 1, value 271828.0
764                         "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
765                         "b304"+ // start group field 70 level 1
766                         "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
767                         "b404"+ // end group field 70 level 1
768                         "d305"+ // start group field 90 level 1
769                         "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
770                         "d405"+ // end group field 90 level 1
771                         "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
772                         "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
773                         "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
774                         "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
775                         "f0123f"+ // field 302, encoding 0, value 63
776                         "f8127f"+ // field 303, encoding 0, value 127
777                         "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
778                         "90193f"+ // field 402, encoding 0, value 63
779                         "98197f") // field 403, encoding 0, value 127
780
781 }
782
783 // All required fields set, defaults provided, all repeated fields given two values.
784 func TestEncodeDecode5(t *testing.T) {
785         pb := initGoTest(true)
786         pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
787         pb.F_BoolRepeated = []bool{false, true}
788         pb.F_Int32Repeated = []int32{32, 33}
789         pb.F_Int64Repeated = []int64{64, 65}
790         pb.F_Fixed32Repeated = []uint32{3232, 3333}
791         pb.F_Fixed64Repeated = []uint64{6464, 6565}
792         pb.F_Uint32Repeated = []uint32{323232, 333333}
793         pb.F_Uint64Repeated = []uint64{646464, 656565}
794         pb.F_FloatRepeated = []float32{32., 33.}
795         pb.F_DoubleRepeated = []float64{64., 65.}
796         pb.F_StringRepeated = []string{"hello", "sailor"}
797         pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
798         pb.F_Sint32Repeated = []int32{32, -32}
799         pb.F_Sint64Repeated = []int64{64, -64}
800         pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
801
802         overify(t, pb,
803                 "0807"+ // field 1, encoding 0, value 7
804                         "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
805                         "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
806                         "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
807                         "5001"+ // field 10, encoding 0, value 1
808                         "5803"+ // field 11, encoding 0, value 3
809                         "6006"+ // field 12, encoding 0, value 6
810                         "6d20000000"+ // field 13, encoding 5, value 32
811                         "714000000000000000"+ // field 14, encoding 1, value 64
812                         "78a019"+ // field 15, encoding 0, value 3232
813                         "8001c032"+ // field 16, encoding 0, value 6464
814                         "8d0100004a45"+ // field 17, encoding 5, value 3232.0
815                         "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
816                         "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
817                         "a00100"+ // field 20, encoding 0, value 0
818                         "a00101"+ // field 20, encoding 0, value 1
819                         "a80120"+ // field 21, encoding 0, value 32
820                         "a80121"+ // field 21, encoding 0, value 33
821                         "b00140"+ // field 22, encoding 0, value 64
822                         "b00141"+ // field 22, encoding 0, value 65
823                         "bd01a00c0000"+ // field 23, encoding 5, value 3232
824                         "bd01050d0000"+ // field 23, encoding 5, value 3333
825                         "c1014019000000000000"+ // field 24, encoding 1, value 6464
826                         "c101a519000000000000"+ // field 24, encoding 1, value 6565
827                         "c801a0dd13"+ // field 25, encoding 0, value 323232
828                         "c80195ac14"+ // field 25, encoding 0, value 333333
829                         "d001c0ba27"+ // field 26, encoding 0, value 646464
830                         "d001b58928"+ // field 26, encoding 0, value 656565
831                         "dd0100000042"+ // field 27, encoding 5, value 32.0
832                         "dd0100000442"+ // field 27, encoding 5, value 33.0
833                         "e1010000000000005040"+ // field 28, encoding 1, value 64.0
834                         "e1010000000000405040"+ // field 28, encoding 1, value 65.0
835                         "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
836                         "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
837                         "c00201"+ // field 40, encoding 0, value 1
838                         "c80220"+ // field 41, encoding 0, value 32
839                         "d00240"+ // field 42, encoding 0, value 64
840                         "dd0240010000"+ // field 43, encoding 5, value 320
841                         "e1028002000000000000"+ // field 44, encoding 1, value 640
842                         "e8028019"+ // field 45, encoding 0, value 3200
843                         "f0028032"+ // field 46, encoding 0, value 6400
844                         "fd02e0659948"+ // field 47, encoding 5, value 314159.0
845                         "81030000000050971041"+ // field 48, encoding 1, value 271828.0
846                         "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
847                         "b304"+ // start group field 70 level 1
848                         "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
849                         "b404"+ // end group field 70 level 1
850                         "8305"+ // start group field 80 level 1
851                         "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
852                         "8405"+ // end group field 80 level 1
853                         "8305"+ // start group field 80 level 1
854                         "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
855                         "8405"+ // end group field 80 level 1
856                         "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
857                         "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
858                         "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
859                         "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
860                         "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
861                         "d00c40"+ // field 202, encoding 0, value 32
862                         "d00c3f"+ // field 202, encoding 0, value -32
863                         "d80c8001"+ // field 203, encoding 0, value 64
864                         "d80c7f"+ // field 203, encoding 0, value -64
865                         "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
866                         "90193f"+ // field 402, encoding 0, value 63
867                         "98197f") // field 403, encoding 0, value 127
868
869 }
870
871 // All required fields set, all packed repeated fields given two values.
872 func TestEncodeDecode6(t *testing.T) {
873         pb := initGoTest(false)
874         pb.F_BoolRepeatedPacked = []bool{false, true}
875         pb.F_Int32RepeatedPacked = []int32{32, 33}
876         pb.F_Int64RepeatedPacked = []int64{64, 65}
877         pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
878         pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
879         pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
880         pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
881         pb.F_FloatRepeatedPacked = []float32{32., 33.}
882         pb.F_DoubleRepeatedPacked = []float64{64., 65.}
883         pb.F_Sint32RepeatedPacked = []int32{32, -32}
884         pb.F_Sint64RepeatedPacked = []int64{64, -64}
885
886         overify(t, pb,
887                 "0807"+ // field 1, encoding 0, value 7
888                         "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
889                         "5001"+ // field 10, encoding 0, value 1
890                         "5803"+ // field 11, encoding 0, value 3
891                         "6006"+ // field 12, encoding 0, value 6
892                         "6d20000000"+ // field 13, encoding 5, value 32
893                         "714000000000000000"+ // field 14, encoding 1, value 64
894                         "78a019"+ // field 15, encoding 0, value 3232
895                         "8001c032"+ // field 16, encoding 0, value 6464
896                         "8d0100004a45"+ // field 17, encoding 5, value 3232.0
897                         "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
898                         "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
899                         "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
900                         "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
901                         "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
902                         "aa0308"+ // field 53, encoding 2, 8 bytes
903                         "a00c0000050d0000"+ // value 3232, value 3333
904                         "b20310"+ // field 54, encoding 2, 16 bytes
905                         "4019000000000000a519000000000000"+ // value 6464, value 6565
906                         "ba0306"+ // field 55, encoding 2, 6 bytes
907                         "a0dd1395ac14"+ // value 323232, value 333333
908                         "c20306"+ // field 56, encoding 2, 6 bytes
909                         "c0ba27b58928"+ // value 646464, value 656565
910                         "ca0308"+ // field 57, encoding 2, 8 bytes
911                         "0000004200000442"+ // value 32.0, value 33.0
912                         "d20310"+ // field 58, encoding 2, 16 bytes
913                         "00000000000050400000000000405040"+ // value 64.0, value 65.0
914                         "b304"+ // start group field 70 level 1
915                         "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
916                         "b404"+ // end group field 70 level 1
917                         "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
918                         "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
919                         "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
920                         "b21f02"+ // field 502, encoding 2, 2 bytes
921                         "403f"+ // value 32, value -32
922                         "ba1f03"+ // field 503, encoding 2, 3 bytes
923                         "80017f") // value 64, value -64
924 }
925
926 // Test that we can encode empty bytes fields.
927 func TestEncodeDecodeBytes1(t *testing.T) {
928         pb := initGoTest(false)
929
930         // Create our bytes
931         pb.F_BytesRequired = []byte{}
932         pb.F_BytesRepeated = [][]byte{{}}
933         pb.F_BytesOptional = []byte{}
934
935         d, err := Marshal(pb)
936         if err != nil {
937                 t.Error(err)
938         }
939
940         pbd := new(GoTest)
941         if err := Unmarshal(d, pbd); err != nil {
942                 t.Error(err)
943         }
944
945         if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
946                 t.Error("required empty bytes field is incorrect")
947         }
948         if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
949                 t.Error("repeated empty bytes field is incorrect")
950         }
951         if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
952                 t.Error("optional empty bytes field is incorrect")
953         }
954 }
955
956 // Test that we encode nil-valued fields of a repeated bytes field correctly.
957 // Since entries in a repeated field cannot be nil, nil must mean empty value.
958 func TestEncodeDecodeBytes2(t *testing.T) {
959         pb := initGoTest(false)
960
961         // Create our bytes
962         pb.F_BytesRepeated = [][]byte{nil}
963
964         d, err := Marshal(pb)
965         if err != nil {
966                 t.Error(err)
967         }
968
969         pbd := new(GoTest)
970         if err := Unmarshal(d, pbd); err != nil {
971                 t.Error(err)
972         }
973
974         if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
975                 t.Error("Unexpected value for repeated bytes field")
976         }
977 }
978
979 // All required fields set, defaults provided, all repeated fields given two values.
980 func TestSkippingUnrecognizedFields(t *testing.T) {
981         o := old()
982         pb := initGoTestField()
983
984         // Marshal it normally.
985         o.Marshal(pb)
986
987         // Now new a GoSkipTest record.
988         skip := &GoSkipTest{
989                 SkipInt32:   Int32(32),
990                 SkipFixed32: Uint32(3232),
991                 SkipFixed64: Uint64(6464),
992                 SkipString:  String("skipper"),
993                 Skipgroup: &GoSkipTest_SkipGroup{
994                         GroupInt32:  Int32(75),
995                         GroupString: String("wxyz"),
996                 },
997         }
998
999         // Marshal it into same buffer.
1000         o.Marshal(skip)
1001
1002         pbd := new(GoTestField)
1003         o.Unmarshal(pbd)
1004
1005         // The __unrecognized field should be a marshaling of GoSkipTest
1006         skipd := new(GoSkipTest)
1007
1008         o.SetBuf(pbd.XXX_unrecognized)
1009         o.Unmarshal(skipd)
1010
1011         if *skipd.SkipInt32 != *skip.SkipInt32 {
1012                 t.Error("skip int32", skipd.SkipInt32)
1013         }
1014         if *skipd.SkipFixed32 != *skip.SkipFixed32 {
1015                 t.Error("skip fixed32", skipd.SkipFixed32)
1016         }
1017         if *skipd.SkipFixed64 != *skip.SkipFixed64 {
1018                 t.Error("skip fixed64", skipd.SkipFixed64)
1019         }
1020         if *skipd.SkipString != *skip.SkipString {
1021                 t.Error("skip string", *skipd.SkipString)
1022         }
1023         if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
1024                 t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
1025         }
1026         if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
1027                 t.Error("skip group string", *skipd.Skipgroup.GroupString)
1028         }
1029 }
1030
1031 // Check that unrecognized fields of a submessage are preserved.
1032 func TestSubmessageUnrecognizedFields(t *testing.T) {
1033         nm := &NewMessage{
1034                 Nested: &NewMessage_Nested{
1035                         Name:      String("Nigel"),
1036                         FoodGroup: String("carbs"),
1037                 },
1038         }
1039         b, err := Marshal(nm)
1040         if err != nil {
1041                 t.Fatalf("Marshal of NewMessage: %v", err)
1042         }
1043
1044         // Unmarshal into an OldMessage.
1045         om := new(OldMessage)
1046         if err := Unmarshal(b, om); err != nil {
1047                 t.Fatalf("Unmarshal to OldMessage: %v", err)
1048         }
1049         exp := &OldMessage{
1050                 Nested: &OldMessage_Nested{
1051                         Name: String("Nigel"),
1052                         // normal protocol buffer users should not do this
1053                         XXX_unrecognized: []byte("\x12\x05carbs"),
1054                 },
1055         }
1056         if !Equal(om, exp) {
1057                 t.Errorf("om = %v, want %v", om, exp)
1058         }
1059
1060         // Clone the OldMessage.
1061         om = Clone(om).(*OldMessage)
1062         if !Equal(om, exp) {
1063                 t.Errorf("Clone(om) = %v, want %v", om, exp)
1064         }
1065
1066         // Marshal the OldMessage, then unmarshal it into an empty NewMessage.
1067         if b, err = Marshal(om); err != nil {
1068                 t.Fatalf("Marshal of OldMessage: %v", err)
1069         }
1070         t.Logf("Marshal(%v) -> %q", om, b)
1071         nm2 := new(NewMessage)
1072         if err := Unmarshal(b, nm2); err != nil {
1073                 t.Fatalf("Unmarshal to NewMessage: %v", err)
1074         }
1075         if !Equal(nm, nm2) {
1076                 t.Errorf("NewMessage round-trip: %v => %v", nm, nm2)
1077         }
1078 }
1079
1080 // Check that an int32 field can be upgraded to an int64 field.
1081 func TestNegativeInt32(t *testing.T) {
1082         om := &OldMessage{
1083                 Num: Int32(-1),
1084         }
1085         b, err := Marshal(om)
1086         if err != nil {
1087                 t.Fatalf("Marshal of OldMessage: %v", err)
1088         }
1089
1090         // Check the size. It should be 11 bytes;
1091         // 1 for the field/wire type, and 10 for the negative number.
1092         if len(b) != 11 {
1093                 t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b)
1094         }
1095
1096         // Unmarshal into a NewMessage.
1097         nm := new(NewMessage)
1098         if err := Unmarshal(b, nm); err != nil {
1099                 t.Fatalf("Unmarshal to NewMessage: %v", err)
1100         }
1101         want := &NewMessage{
1102                 Num: Int64(-1),
1103         }
1104         if !Equal(nm, want) {
1105                 t.Errorf("nm = %v, want %v", nm, want)
1106         }
1107 }
1108
1109 // Check that we can grow an array (repeated field) to have many elements.
1110 // This test doesn't depend only on our encoding; for variety, it makes sure
1111 // we create, encode, and decode the correct contents explicitly.  It's therefore
1112 // a bit messier.
1113 // This test also uses (and hence tests) the Marshal/Unmarshal functions
1114 // instead of the methods.
1115 func TestBigRepeated(t *testing.T) {
1116         pb := initGoTest(true)
1117
1118         // Create the arrays
1119         const N = 50 // Internally the library starts much smaller.
1120         pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
1121         pb.F_Sint64Repeated = make([]int64, N)
1122         pb.F_Sint32Repeated = make([]int32, N)
1123         pb.F_BytesRepeated = make([][]byte, N)
1124         pb.F_StringRepeated = make([]string, N)
1125         pb.F_DoubleRepeated = make([]float64, N)
1126         pb.F_FloatRepeated = make([]float32, N)
1127         pb.F_Uint64Repeated = make([]uint64, N)
1128         pb.F_Uint32Repeated = make([]uint32, N)
1129         pb.F_Fixed64Repeated = make([]uint64, N)
1130         pb.F_Fixed32Repeated = make([]uint32, N)
1131         pb.F_Int64Repeated = make([]int64, N)
1132         pb.F_Int32Repeated = make([]int32, N)
1133         pb.F_BoolRepeated = make([]bool, N)
1134         pb.RepeatedField = make([]*GoTestField, N)
1135
1136         // Fill in the arrays with checkable values.
1137         igtf := initGoTestField()
1138         igtrg := initGoTest_RepeatedGroup()
1139         for i := 0; i < N; i++ {
1140                 pb.Repeatedgroup[i] = igtrg
1141                 pb.F_Sint64Repeated[i] = int64(i)
1142                 pb.F_Sint32Repeated[i] = int32(i)
1143                 s := fmt.Sprint(i)
1144                 pb.F_BytesRepeated[i] = []byte(s)
1145                 pb.F_StringRepeated[i] = s
1146                 pb.F_DoubleRepeated[i] = float64(i)
1147                 pb.F_FloatRepeated[i] = float32(i)
1148                 pb.F_Uint64Repeated[i] = uint64(i)
1149                 pb.F_Uint32Repeated[i] = uint32(i)
1150                 pb.F_Fixed64Repeated[i] = uint64(i)
1151                 pb.F_Fixed32Repeated[i] = uint32(i)
1152                 pb.F_Int64Repeated[i] = int64(i)
1153                 pb.F_Int32Repeated[i] = int32(i)
1154                 pb.F_BoolRepeated[i] = i%2 == 0
1155                 pb.RepeatedField[i] = igtf
1156         }
1157
1158         // Marshal.
1159         buf, _ := Marshal(pb)
1160
1161         // Now test Unmarshal by recreating the original buffer.
1162         pbd := new(GoTest)
1163         Unmarshal(buf, pbd)
1164
1165         // Check the checkable values
1166         for i := uint64(0); i < N; i++ {
1167                 if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
1168                         t.Error("pbd.Repeatedgroup bad")
1169                 }
1170                 var x uint64
1171                 x = uint64(pbd.F_Sint64Repeated[i])
1172                 if x != i {
1173                         t.Error("pbd.F_Sint64Repeated bad", x, i)
1174                 }
1175                 x = uint64(pbd.F_Sint32Repeated[i])
1176                 if x != i {
1177                         t.Error("pbd.F_Sint32Repeated bad", x, i)
1178                 }
1179                 s := fmt.Sprint(i)
1180                 equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
1181                 if pbd.F_StringRepeated[i] != s {
1182                         t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
1183                 }
1184                 x = uint64(pbd.F_DoubleRepeated[i])
1185                 if x != i {
1186                         t.Error("pbd.F_DoubleRepeated bad", x, i)
1187                 }
1188                 x = uint64(pbd.F_FloatRepeated[i])
1189                 if x != i {
1190                         t.Error("pbd.F_FloatRepeated bad", x, i)
1191                 }
1192                 x = pbd.F_Uint64Repeated[i]
1193                 if x != i {
1194                         t.Error("pbd.F_Uint64Repeated bad", x, i)
1195                 }
1196                 x = uint64(pbd.F_Uint32Repeated[i])
1197                 if x != i {
1198                         t.Error("pbd.F_Uint32Repeated bad", x, i)
1199                 }
1200                 x = pbd.F_Fixed64Repeated[i]
1201                 if x != i {
1202                         t.Error("pbd.F_Fixed64Repeated bad", x, i)
1203                 }
1204                 x = uint64(pbd.F_Fixed32Repeated[i])
1205                 if x != i {
1206                         t.Error("pbd.F_Fixed32Repeated bad", x, i)
1207                 }
1208                 x = uint64(pbd.F_Int64Repeated[i])
1209                 if x != i {
1210                         t.Error("pbd.F_Int64Repeated bad", x, i)
1211                 }
1212                 x = uint64(pbd.F_Int32Repeated[i])
1213                 if x != i {
1214                         t.Error("pbd.F_Int32Repeated bad", x, i)
1215                 }
1216                 if pbd.F_BoolRepeated[i] != (i%2 == 0) {
1217                         t.Error("pbd.F_BoolRepeated bad", x, i)
1218                 }
1219                 if pbd.RepeatedField[i] == nil { // TODO: more checking?
1220                         t.Error("pbd.RepeatedField bad")
1221                 }
1222         }
1223 }
1224
1225 // Verify we give a useful message when decoding to the wrong structure type.
1226 func TestTypeMismatch(t *testing.T) {
1227         pb1 := initGoTest(true)
1228
1229         // Marshal
1230         o := old()
1231         o.Marshal(pb1)
1232
1233         // Now Unmarshal it to the wrong type.
1234         pb2 := initGoTestField()
1235         err := o.Unmarshal(pb2)
1236         if err == nil {
1237                 t.Error("expected error, got no error")
1238         } else if !strings.Contains(err.Error(), "bad wiretype") {
1239                 t.Error("expected bad wiretype error, got", err)
1240         }
1241 }
1242
1243 func encodeDecode(t *testing.T, in, out Message, msg string) {
1244         buf, err := Marshal(in)
1245         if err != nil {
1246                 t.Fatalf("failed marshaling %v: %v", msg, err)
1247         }
1248         if err := Unmarshal(buf, out); err != nil {
1249                 t.Fatalf("failed unmarshaling %v: %v", msg, err)
1250         }
1251 }
1252
1253 func TestPackedNonPackedDecoderSwitching(t *testing.T) {
1254         np, p := new(NonPackedTest), new(PackedTest)
1255
1256         // non-packed -> packed
1257         np.A = []int32{0, 1, 1, 2, 3, 5}
1258         encodeDecode(t, np, p, "non-packed -> packed")
1259         if !reflect.DeepEqual(np.A, p.B) {
1260                 t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
1261         }
1262
1263         // packed -> non-packed
1264         np.Reset()
1265         p.B = []int32{3, 1, 4, 1, 5, 9}
1266         encodeDecode(t, p, np, "packed -> non-packed")
1267         if !reflect.DeepEqual(p.B, np.A) {
1268                 t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
1269         }
1270 }
1271
1272 func TestProto1RepeatedGroup(t *testing.T) {
1273         pb := &MessageList{
1274                 Message: []*MessageList_Message{
1275                         {
1276                                 Name:  String("blah"),
1277                                 Count: Int32(7),
1278                         },
1279                         // NOTE: pb.Message[1] is a nil
1280                         nil,
1281                 },
1282         }
1283
1284         o := old()
1285         err := o.Marshal(pb)
1286         if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") {
1287                 t.Fatalf("unexpected or no error when marshaling: %v", err)
1288         }
1289 }
1290
1291 // Test that enums work.  Checks for a bug introduced by making enums
1292 // named types instead of int32: newInt32FromUint64 would crash with
1293 // a type mismatch in reflect.PointTo.
1294 func TestEnum(t *testing.T) {
1295         pb := new(GoEnum)
1296         pb.Foo = FOO_FOO1.Enum()
1297         o := old()
1298         if err := o.Marshal(pb); err != nil {
1299                 t.Fatal("error encoding enum:", err)
1300         }
1301         pb1 := new(GoEnum)
1302         if err := o.Unmarshal(pb1); err != nil {
1303                 t.Fatal("error decoding enum:", err)
1304         }
1305         if *pb1.Foo != FOO_FOO1 {
1306                 t.Error("expected 7 but got ", *pb1.Foo)
1307         }
1308 }
1309
1310 // Enum types have String methods. Check that enum fields can be printed.
1311 // We don't care what the value actually is, just as long as it doesn't crash.
1312 func TestPrintingNilEnumFields(t *testing.T) {
1313         pb := new(GoEnum)
1314         _ = fmt.Sprintf("%+v", pb)
1315 }
1316
1317 // Verify that absent required fields cause Marshal/Unmarshal to return errors.
1318 func TestRequiredFieldEnforcement(t *testing.T) {
1319         pb := new(GoTestField)
1320         _, err := Marshal(pb)
1321         if err == nil {
1322                 t.Error("marshal: expected error, got nil")
1323         } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Label") {
1324                 t.Errorf("marshal: bad error type: %v", err)
1325         }
1326
1327         // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
1328         // so simply counting the required fields is insufficient.
1329         // field 1, encoding 2, value "hi"
1330         buf := []byte("\x0A\x02hi\x0A\x02hi")
1331         err = Unmarshal(buf, pb)
1332         if err == nil {
1333                 t.Error("unmarshal: expected error, got nil")
1334         } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "{Unknown}") {
1335                 t.Errorf("unmarshal: bad error type: %v", err)
1336         }
1337 }
1338
1339 // Verify that absent required fields in groups cause Marshal/Unmarshal to return errors.
1340 func TestRequiredFieldEnforcementGroups(t *testing.T) {
1341         pb := &GoTestRequiredGroupField{Group: &GoTestRequiredGroupField_Group{}}
1342         if _, err := Marshal(pb); err == nil {
1343                 t.Error("marshal: expected error, got nil")
1344         } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.Field") {
1345                 t.Errorf("marshal: bad error type: %v", err)
1346         }
1347
1348         buf := []byte{11, 12}
1349         if err := Unmarshal(buf, pb); err == nil {
1350                 t.Error("unmarshal: expected error, got nil")
1351         } else if _, ok := err.(*RequiredNotSetError); !ok || !strings.Contains(err.Error(), "Group.{Unknown}") {
1352                 t.Errorf("unmarshal: bad error type: %v", err)
1353         }
1354 }
1355
1356 func TestTypedNilMarshal(t *testing.T) {
1357         // A typed nil should return ErrNil and not crash.
1358         {
1359                 var m *GoEnum
1360                 if _, err := Marshal(m); err != ErrNil {
1361                         t.Errorf("Marshal(%#v): got %v, want ErrNil", m, err)
1362                 }
1363         }
1364
1365         {
1366                 m := &Communique{Union: &Communique_Msg{nil}}
1367                 if _, err := Marshal(m); err == nil || err == ErrNil {
1368                         t.Errorf("Marshal(%#v): got %v, want errOneofHasNil", m, err)
1369                 }
1370         }
1371 }
1372
1373 // A type that implements the Marshaler interface, but is not nillable.
1374 type nonNillableInt uint64
1375
1376 func (nni nonNillableInt) Marshal() ([]byte, error) {
1377         return EncodeVarint(uint64(nni)), nil
1378 }
1379
1380 type NNIMessage struct {
1381         nni nonNillableInt
1382 }
1383
1384 func (*NNIMessage) Reset()         {}
1385 func (*NNIMessage) String() string { return "" }
1386 func (*NNIMessage) ProtoMessage()  {}
1387
1388 // A type that implements the Marshaler interface and is nillable.
1389 type nillableMessage struct {
1390         x uint64
1391 }
1392
1393 func (nm *nillableMessage) Marshal() ([]byte, error) {
1394         return EncodeVarint(nm.x), nil
1395 }
1396
1397 type NMMessage struct {
1398         nm *nillableMessage
1399 }
1400
1401 func (*NMMessage) Reset()         {}
1402 func (*NMMessage) String() string { return "" }
1403 func (*NMMessage) ProtoMessage()  {}
1404
1405 // Verify a type that uses the Marshaler interface, but has a nil pointer.
1406 func TestNilMarshaler(t *testing.T) {
1407         // Try a struct with a Marshaler field that is nil.
1408         // It should be directly marshable.
1409         nmm := new(NMMessage)
1410         if _, err := Marshal(nmm); err != nil {
1411                 t.Error("unexpected error marshaling nmm: ", err)
1412         }
1413
1414         // Try a struct with a Marshaler field that is not nillable.
1415         nnim := new(NNIMessage)
1416         nnim.nni = 7
1417         var _ Marshaler = nnim.nni // verify it is truly a Marshaler
1418         if _, err := Marshal(nnim); err != nil {
1419                 t.Error("unexpected error marshaling nnim: ", err)
1420         }
1421 }
1422
1423 func TestAllSetDefaults(t *testing.T) {
1424         // Exercise SetDefaults with all scalar field types.
1425         m := &Defaults{
1426                 // NaN != NaN, so override that here.
1427                 F_Nan: Float32(1.7),
1428         }
1429         expected := &Defaults{
1430                 F_Bool:    Bool(true),
1431                 F_Int32:   Int32(32),
1432                 F_Int64:   Int64(64),
1433                 F_Fixed32: Uint32(320),
1434                 F_Fixed64: Uint64(640),
1435                 F_Uint32:  Uint32(3200),
1436                 F_Uint64:  Uint64(6400),
1437                 F_Float:   Float32(314159),
1438                 F_Double:  Float64(271828),
1439                 F_String:  String(`hello, "world!"` + "\n"),
1440                 F_Bytes:   []byte("Bignose"),
1441                 F_Sint32:  Int32(-32),
1442                 F_Sint64:  Int64(-64),
1443                 F_Enum:    Defaults_GREEN.Enum(),
1444                 F_Pinf:    Float32(float32(math.Inf(1))),
1445                 F_Ninf:    Float32(float32(math.Inf(-1))),
1446                 F_Nan:     Float32(1.7),
1447                 StrZero:   String(""),
1448         }
1449         SetDefaults(m)
1450         if !Equal(m, expected) {
1451                 t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected)
1452         }
1453 }
1454
1455 func TestSetDefaultsWithSetField(t *testing.T) {
1456         // Check that a set value is not overridden.
1457         m := &Defaults{
1458                 F_Int32: Int32(12),
1459         }
1460         SetDefaults(m)
1461         if v := m.GetF_Int32(); v != 12 {
1462                 t.Errorf("m.FInt32 = %v, want 12", v)
1463         }
1464 }
1465
1466 func TestSetDefaultsWithSubMessage(t *testing.T) {
1467         m := &OtherMessage{
1468                 Key: Int64(123),
1469                 Inner: &InnerMessage{
1470                         Host: String("gopher"),
1471                 },
1472         }
1473         expected := &OtherMessage{
1474                 Key: Int64(123),
1475                 Inner: &InnerMessage{
1476                         Host: String("gopher"),
1477                         Port: Int32(4000),
1478                 },
1479         }
1480         SetDefaults(m)
1481         if !Equal(m, expected) {
1482                 t.Errorf("\n got %v\nwant %v", m, expected)
1483         }
1484 }
1485
1486 func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) {
1487         m := &MyMessage{
1488                 RepInner: []*InnerMessage{{}},
1489         }
1490         expected := &MyMessage{
1491                 RepInner: []*InnerMessage{{
1492                         Port: Int32(4000),
1493                 }},
1494         }
1495         SetDefaults(m)
1496         if !Equal(m, expected) {
1497                 t.Errorf("\n got %v\nwant %v", m, expected)
1498         }
1499 }
1500
1501 func TestSetDefaultWithRepeatedNonMessage(t *testing.T) {
1502         m := &MyMessage{
1503                 Pet: []string{"turtle", "wombat"},
1504         }
1505         expected := Clone(m)
1506         SetDefaults(m)
1507         if !Equal(m, expected) {
1508                 t.Errorf("\n got %v\nwant %v", m, expected)
1509         }
1510 }
1511
1512 func TestMaximumTagNumber(t *testing.T) {
1513         m := &MaxTag{
1514                 LastField: String("natural goat essence"),
1515         }
1516         buf, err := Marshal(m)
1517         if err != nil {
1518                 t.Fatalf("proto.Marshal failed: %v", err)
1519         }
1520         m2 := new(MaxTag)
1521         if err := Unmarshal(buf, m2); err != nil {
1522                 t.Fatalf("proto.Unmarshal failed: %v", err)
1523         }
1524         if got, want := m2.GetLastField(), *m.LastField; got != want {
1525                 t.Errorf("got %q, want %q", got, want)
1526         }
1527 }
1528
1529 func TestJSON(t *testing.T) {
1530         m := &MyMessage{
1531                 Count: Int32(4),
1532                 Pet:   []string{"bunny", "kitty"},
1533                 Inner: &InnerMessage{
1534                         Host: String("cauchy"),
1535                 },
1536                 Bikeshed: MyMessage_GREEN.Enum(),
1537         }
1538         const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}`
1539
1540         b, err := json.Marshal(m)
1541         if err != nil {
1542                 t.Fatalf("json.Marshal failed: %v", err)
1543         }
1544         s := string(b)
1545         if s != expected {
1546                 t.Errorf("got  %s\nwant %s", s, expected)
1547         }
1548
1549         received := new(MyMessage)
1550         if err := json.Unmarshal(b, received); err != nil {
1551                 t.Fatalf("json.Unmarshal failed: %v", err)
1552         }
1553         if !Equal(received, m) {
1554                 t.Fatalf("got %s, want %s", received, m)
1555         }
1556
1557         // Test unmarshalling of JSON with symbolic enum name.
1558         const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}`
1559         received.Reset()
1560         if err := json.Unmarshal([]byte(old), received); err != nil {
1561                 t.Fatalf("json.Unmarshal failed: %v", err)
1562         }
1563         if !Equal(received, m) {
1564                 t.Fatalf("got %s, want %s", received, m)
1565         }
1566 }
1567
1568 func TestBadWireType(t *testing.T) {
1569         b := []byte{7<<3 | 6} // field 7, wire type 6
1570         pb := new(OtherMessage)
1571         if err := Unmarshal(b, pb); err == nil {
1572                 t.Errorf("Unmarshal did not fail")
1573         } else if !strings.Contains(err.Error(), "unknown wire type") {
1574                 t.Errorf("wrong error: %v", err)
1575         }
1576 }
1577
1578 func TestBytesWithInvalidLength(t *testing.T) {
1579         // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
1580         b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0}
1581         Unmarshal(b, new(MyMessage))
1582 }
1583
1584 func TestLengthOverflow(t *testing.T) {
1585         // Overflowing a length should not panic.
1586         b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01}
1587         Unmarshal(b, new(MyMessage))
1588 }
1589
1590 func TestVarintOverflow(t *testing.T) {
1591         // Overflowing a 64-bit length should not be allowed.
1592         b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01}
1593         if err := Unmarshal(b, new(MyMessage)); err == nil {
1594                 t.Fatalf("Overflowed uint64 length without error")
1595         }
1596 }
1597
1598 func TestUnmarshalFuzz(t *testing.T) {
1599         const N = 1000
1600         seed := time.Now().UnixNano()
1601         t.Logf("RNG seed is %d", seed)
1602         rng := rand.New(rand.NewSource(seed))
1603         buf := make([]byte, 20)
1604         for i := 0; i < N; i++ {
1605                 for j := range buf {
1606                         buf[j] = byte(rng.Intn(256))
1607                 }
1608                 fuzzUnmarshal(t, buf)
1609         }
1610 }
1611
1612 func TestMergeMessages(t *testing.T) {
1613         pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}}
1614         data, err := Marshal(pb)
1615         if err != nil {
1616                 t.Fatalf("Marshal: %v", err)
1617         }
1618
1619         pb1 := new(MessageList)
1620         if err := Unmarshal(data, pb1); err != nil {
1621                 t.Fatalf("first Unmarshal: %v", err)
1622         }
1623         if err := Unmarshal(data, pb1); err != nil {
1624                 t.Fatalf("second Unmarshal: %v", err)
1625         }
1626         if len(pb1.Message) != 1 {
1627                 t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message))
1628         }
1629
1630         pb2 := new(MessageList)
1631         if err := UnmarshalMerge(data, pb2); err != nil {
1632                 t.Fatalf("first UnmarshalMerge: %v", err)
1633         }
1634         if err := UnmarshalMerge(data, pb2); err != nil {
1635                 t.Fatalf("second UnmarshalMerge: %v", err)
1636         }
1637         if len(pb2.Message) != 2 {
1638                 t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message))
1639         }
1640 }
1641
1642 func TestExtensionMarshalOrder(t *testing.T) {
1643         m := &MyMessage{Count: Int(123)}
1644         if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil {
1645                 t.Fatalf("SetExtension: %v", err)
1646         }
1647         if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil {
1648                 t.Fatalf("SetExtension: %v", err)
1649         }
1650         if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil {
1651                 t.Fatalf("SetExtension: %v", err)
1652         }
1653
1654         // Serialize m several times, and check we get the same bytes each time.
1655         var orig []byte
1656         for i := 0; i < 100; i++ {
1657                 b, err := Marshal(m)
1658                 if err != nil {
1659                         t.Fatalf("Marshal: %v", err)
1660                 }
1661                 if i == 0 {
1662                         orig = b
1663                         continue
1664                 }
1665                 if !bytes.Equal(b, orig) {
1666                         t.Errorf("Bytes differ on attempt #%d", i)
1667                 }
1668         }
1669 }
1670
1671 // Many extensions, because small maps might not iterate differently on each iteration.
1672 var exts = []*ExtensionDesc{
1673         E_X201,
1674         E_X202,
1675         E_X203,
1676         E_X204,
1677         E_X205,
1678         E_X206,
1679         E_X207,
1680         E_X208,
1681         E_X209,
1682         E_X210,
1683         E_X211,
1684         E_X212,
1685         E_X213,
1686         E_X214,
1687         E_X215,
1688         E_X216,
1689         E_X217,
1690         E_X218,
1691         E_X219,
1692         E_X220,
1693         E_X221,
1694         E_X222,
1695         E_X223,
1696         E_X224,
1697         E_X225,
1698         E_X226,
1699         E_X227,
1700         E_X228,
1701         E_X229,
1702         E_X230,
1703         E_X231,
1704         E_X232,
1705         E_X233,
1706         E_X234,
1707         E_X235,
1708         E_X236,
1709         E_X237,
1710         E_X238,
1711         E_X239,
1712         E_X240,
1713         E_X241,
1714         E_X242,
1715         E_X243,
1716         E_X244,
1717         E_X245,
1718         E_X246,
1719         E_X247,
1720         E_X248,
1721         E_X249,
1722         E_X250,
1723 }
1724
1725 func TestMessageSetMarshalOrder(t *testing.T) {
1726         m := &MyMessageSet{}
1727         for _, x := range exts {
1728                 if err := SetExtension(m, x, &Empty{}); err != nil {
1729                         t.Fatalf("SetExtension: %v", err)
1730                 }
1731         }
1732
1733         buf, err := Marshal(m)
1734         if err != nil {
1735                 t.Fatalf("Marshal: %v", err)
1736         }
1737
1738         // Serialize m several times, and check we get the same bytes each time.
1739         for i := 0; i < 10; i++ {
1740                 b1, err := Marshal(m)
1741                 if err != nil {
1742                         t.Fatalf("Marshal: %v", err)
1743                 }
1744                 if !bytes.Equal(b1, buf) {
1745                         t.Errorf("Bytes differ on re-Marshal #%d", i)
1746                 }
1747
1748                 m2 := &MyMessageSet{}
1749                 if err := Unmarshal(buf, m2); err != nil {
1750                         t.Errorf("Unmarshal: %v", err)
1751                 }
1752                 b2, err := Marshal(m2)
1753                 if err != nil {
1754                         t.Errorf("re-Marshal: %v", err)
1755                 }
1756                 if !bytes.Equal(b2, buf) {
1757                         t.Errorf("Bytes differ on round-trip #%d", i)
1758                 }
1759         }
1760 }
1761
1762 func TestUnmarshalMergesMessages(t *testing.T) {
1763         // If a nested message occurs twice in the input,
1764         // the fields should be merged when decoding.
1765         a := &OtherMessage{
1766                 Key: Int64(123),
1767                 Inner: &InnerMessage{
1768                         Host: String("polhode"),
1769                         Port: Int32(1234),
1770                 },
1771         }
1772         aData, err := Marshal(a)
1773         if err != nil {
1774                 t.Fatalf("Marshal(a): %v", err)
1775         }
1776         b := &OtherMessage{
1777                 Weight: Float32(1.2),
1778                 Inner: &InnerMessage{
1779                         Host:      String("herpolhode"),
1780                         Connected: Bool(true),
1781                 },
1782         }
1783         bData, err := Marshal(b)
1784         if err != nil {
1785                 t.Fatalf("Marshal(b): %v", err)
1786         }
1787         want := &OtherMessage{
1788                 Key:    Int64(123),
1789                 Weight: Float32(1.2),
1790                 Inner: &InnerMessage{
1791                         Host:      String("herpolhode"),
1792                         Port:      Int32(1234),
1793                         Connected: Bool(true),
1794                 },
1795         }
1796         got := new(OtherMessage)
1797         if err := Unmarshal(append(aData, bData...), got); err != nil {
1798                 t.Fatalf("Unmarshal: %v", err)
1799         }
1800         if !Equal(got, want) {
1801                 t.Errorf("\n got %v\nwant %v", got, want)
1802         }
1803 }
1804
1805 func TestEncodingSizes(t *testing.T) {
1806         tests := []struct {
1807                 m Message
1808                 n int
1809         }{
1810                 {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6},
1811                 {&Defaults{F_Int32: Int32(math.MinInt32)}, 11},
1812                 {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6},
1813                 {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6},
1814         }
1815         for _, test := range tests {
1816                 b, err := Marshal(test.m)
1817                 if err != nil {
1818                         t.Errorf("Marshal(%v): %v", test.m, err)
1819                         continue
1820                 }
1821                 if len(b) != test.n {
1822                         t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n)
1823                 }
1824         }
1825 }
1826
1827 func TestRequiredNotSetError(t *testing.T) {
1828         pb := initGoTest(false)
1829         pb.RequiredField.Label = nil
1830         pb.F_Int32Required = nil
1831         pb.F_Int64Required = nil
1832
1833         expected := "0807" + // field 1, encoding 0, value 7
1834                 "2206" + "120474797065" + // field 4, encoding 2 (GoTestField)
1835                 "5001" + // field 10, encoding 0, value 1
1836                 "6d20000000" + // field 13, encoding 5, value 0x20
1837                 "714000000000000000" + // field 14, encoding 1, value 0x40
1838                 "78a019" + // field 15, encoding 0, value 0xca0 = 3232
1839                 "8001c032" + // field 16, encoding 0, value 0x1940 = 6464
1840                 "8d0100004a45" + // field 17, encoding 5, value 3232.0
1841                 "9101000000000040b940" + // field 18, encoding 1, value 6464.0
1842                 "9a0106" + "737472696e67" + // field 19, encoding 2, string "string"
1843                 "b304" + // field 70, encoding 3, start group
1844                 "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required"
1845                 "b404" + // field 70, encoding 4, end group
1846                 "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes"
1847                 "b0063f" + // field 102, encoding 0, 0x3f zigzag32
1848                 "b8067f" // field 103, encoding 0, 0x7f zigzag64
1849
1850         o := old()
1851         bytes, err := Marshal(pb)
1852         if _, ok := err.(*RequiredNotSetError); !ok {
1853                 fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err)
1854                 o.DebugPrint("", bytes)
1855                 t.Fatalf("expected = %s", expected)
1856         }
1857         if strings.Index(err.Error(), "RequiredField.Label") < 0 {
1858                 t.Errorf("marshal-1 wrong err msg: %v", err)
1859         }
1860         if !equal(bytes, expected, t) {
1861                 o.DebugPrint("neq 1", bytes)
1862                 t.Fatalf("expected = %s", expected)
1863         }
1864
1865         // Now test Unmarshal by recreating the original buffer.
1866         pbd := new(GoTest)
1867         err = Unmarshal(bytes, pbd)
1868         if _, ok := err.(*RequiredNotSetError); !ok {
1869                 t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err)
1870                 o.DebugPrint("", bytes)
1871                 t.Fatalf("string = %s", expected)
1872         }
1873         if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 {
1874                 t.Errorf("unmarshal wrong err msg: %v", err)
1875         }
1876         bytes, err = Marshal(pbd)
1877         if _, ok := err.(*RequiredNotSetError); !ok {
1878                 t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err)
1879                 o.DebugPrint("", bytes)
1880                 t.Fatalf("string = %s", expected)
1881         }
1882         if strings.Index(err.Error(), "RequiredField.Label") < 0 {
1883                 t.Errorf("marshal-2 wrong err msg: %v", err)
1884         }
1885         if !equal(bytes, expected, t) {
1886                 o.DebugPrint("neq 2", bytes)
1887                 t.Fatalf("string = %s", expected)
1888         }
1889 }
1890
1891 func fuzzUnmarshal(t *testing.T, data []byte) {
1892         defer func() {
1893                 if e := recover(); e != nil {
1894                         t.Errorf("These bytes caused a panic: %+v", data)
1895                         t.Logf("Stack:\n%s", debug.Stack())
1896                         t.FailNow()
1897                 }
1898         }()
1899
1900         pb := new(MyMessage)
1901         Unmarshal(data, pb)
1902 }
1903
1904 func TestMapFieldMarshal(t *testing.T) {
1905         m := &MessageWithMap{
1906                 NameMapping: map[int32]string{
1907                         1: "Rob",
1908                         4: "Ian",
1909                         8: "Dave",
1910                 },
1911         }
1912         b, err := Marshal(m)
1913         if err != nil {
1914                 t.Fatalf("Marshal: %v", err)
1915         }
1916
1917         // b should be the concatenation of these three byte sequences in some order.
1918         parts := []string{
1919                 "\n\a\b\x01\x12\x03Rob",
1920                 "\n\a\b\x04\x12\x03Ian",
1921                 "\n\b\b\x08\x12\x04Dave",
1922         }
1923         ok := false
1924         for i := range parts {
1925                 for j := range parts {
1926                         if j == i {
1927                                 continue
1928                         }
1929                         for k := range parts {
1930                                 if k == i || k == j {
1931                                         continue
1932                                 }
1933                                 try := parts[i] + parts[j] + parts[k]
1934                                 if bytes.Equal(b, []byte(try)) {
1935                                         ok = true
1936                                         break
1937                                 }
1938                         }
1939                 }
1940         }
1941         if !ok {
1942                 t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2])
1943         }
1944         t.Logf("FYI b: %q", b)
1945
1946         (new(Buffer)).DebugPrint("Dump of b", b)
1947 }
1948
1949 func TestMapFieldRoundTrips(t *testing.T) {
1950         m := &MessageWithMap{
1951                 NameMapping: map[int32]string{
1952                         1: "Rob",
1953                         4: "Ian",
1954                         8: "Dave",
1955                 },
1956                 MsgMapping: map[int64]*FloatingPoint{
1957                         0x7001: &FloatingPoint{F: Float64(2.0)},
1958                 },
1959                 ByteMapping: map[bool][]byte{
1960                         false: []byte("that's not right!"),
1961                         true:  []byte("aye, 'tis true!"),
1962                 },
1963         }
1964         b, err := Marshal(m)
1965         if err != nil {
1966                 t.Fatalf("Marshal: %v", err)
1967         }
1968         t.Logf("FYI b: %q", b)
1969         m2 := new(MessageWithMap)
1970         if err := Unmarshal(b, m2); err != nil {
1971                 t.Fatalf("Unmarshal: %v", err)
1972         }
1973         for _, pair := range [][2]interface{}{
1974                 {m.NameMapping, m2.NameMapping},
1975                 {m.MsgMapping, m2.MsgMapping},
1976                 {m.ByteMapping, m2.ByteMapping},
1977         } {
1978                 if !reflect.DeepEqual(pair[0], pair[1]) {
1979                         t.Errorf("Map did not survive a round trip.\ninitial: %v\n  final: %v", pair[0], pair[1])
1980                 }
1981         }
1982 }
1983
1984 func TestMapFieldWithNil(t *testing.T) {
1985         m1 := &MessageWithMap{
1986                 MsgMapping: map[int64]*FloatingPoint{
1987                         1: nil,
1988                 },
1989         }
1990         b, err := Marshal(m1)
1991         if err != nil {
1992                 t.Fatalf("Marshal: %v", err)
1993         }
1994         m2 := new(MessageWithMap)
1995         if err := Unmarshal(b, m2); err != nil {
1996                 t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
1997         }
1998         if v, ok := m2.MsgMapping[1]; !ok {
1999                 t.Error("msg_mapping[1] not present")
2000         } else if v != nil {
2001                 t.Errorf("msg_mapping[1] not nil: %v", v)
2002         }
2003 }
2004
2005 func TestMapFieldWithNilBytes(t *testing.T) {
2006         m1 := &MessageWithMap{
2007                 ByteMapping: map[bool][]byte{
2008                         false: []byte{},
2009                         true:  nil,
2010                 },
2011         }
2012         n := Size(m1)
2013         b, err := Marshal(m1)
2014         if err != nil {
2015                 t.Fatalf("Marshal: %v", err)
2016         }
2017         if n != len(b) {
2018                 t.Errorf("Size(m1) = %d; want len(Marshal(m1)) = %d", n, len(b))
2019         }
2020         m2 := new(MessageWithMap)
2021         if err := Unmarshal(b, m2); err != nil {
2022                 t.Fatalf("Unmarshal: %v, got these bytes: %v", err, b)
2023         }
2024         if v, ok := m2.ByteMapping[false]; !ok {
2025                 t.Error("byte_mapping[false] not present")
2026         } else if len(v) != 0 {
2027                 t.Errorf("byte_mapping[false] not empty: %#v", v)
2028         }
2029         if v, ok := m2.ByteMapping[true]; !ok {
2030                 t.Error("byte_mapping[true] not present")
2031         } else if len(v) != 0 {
2032                 t.Errorf("byte_mapping[true] not empty: %#v", v)
2033         }
2034 }
2035
2036 func TestDecodeMapFieldMissingKey(t *testing.T) {
2037         b := []byte{
2038                 0x0A, 0x03, // message, tag 1 (name_mapping), of length 3 bytes
2039                 // no key
2040                 0x12, 0x01, 0x6D, // string value of length 1 byte, value "m"
2041         }
2042         got := &MessageWithMap{}
2043         err := Unmarshal(b, got)
2044         if err != nil {
2045                 t.Fatalf("failed to marshal map with missing key: %v", err)
2046         }
2047         want := &MessageWithMap{NameMapping: map[int32]string{0: "m"}}
2048         if !Equal(got, want) {
2049                 t.Errorf("Unmarshaled map with no key was not as expected. got: %v, want %v", got, want)
2050         }
2051 }
2052
2053 func TestDecodeMapFieldMissingValue(t *testing.T) {
2054         b := []byte{
2055                 0x0A, 0x02, // message, tag 1 (name_mapping), of length 2 bytes
2056                 0x08, 0x01, // varint key, value 1
2057                 // no value
2058         }
2059         got := &MessageWithMap{}
2060         err := Unmarshal(b, got)
2061         if err != nil {
2062                 t.Fatalf("failed to marshal map with missing value: %v", err)
2063         }
2064         want := &MessageWithMap{NameMapping: map[int32]string{1: ""}}
2065         if !Equal(got, want) {
2066                 t.Errorf("Unmarshaled map with no value was not as expected. got: %v, want %v", got, want)
2067         }
2068 }
2069
2070 func TestOneof(t *testing.T) {
2071         m := &Communique{}
2072         b, err := Marshal(m)
2073         if err != nil {
2074                 t.Fatalf("Marshal of empty message with oneof: %v", err)
2075         }
2076         if len(b) != 0 {
2077                 t.Errorf("Marshal of empty message yielded too many bytes: %v", b)
2078         }
2079
2080         m = &Communique{
2081                 Union: &Communique_Name{"Barry"},
2082         }
2083
2084         // Round-trip.
2085         b, err = Marshal(m)
2086         if err != nil {
2087                 t.Fatalf("Marshal of message with oneof: %v", err)
2088         }
2089         if len(b) != 7 { // name tag/wire (1) + name len (1) + name (5)
2090                 t.Errorf("Incorrect marshal of message with oneof: %v", b)
2091         }
2092         m.Reset()
2093         if err := Unmarshal(b, m); err != nil {
2094                 t.Fatalf("Unmarshal of message with oneof: %v", err)
2095         }
2096         if x, ok := m.Union.(*Communique_Name); !ok || x.Name != "Barry" {
2097                 t.Errorf("After round trip, Union = %+v", m.Union)
2098         }
2099         if name := m.GetName(); name != "Barry" {
2100                 t.Errorf("After round trip, GetName = %q, want %q", name, "Barry")
2101         }
2102
2103         // Let's try with a message in the oneof.
2104         m.Union = &Communique_Msg{&Strings{StringField: String("deep deep string")}}
2105         b, err = Marshal(m)
2106         if err != nil {
2107                 t.Fatalf("Marshal of message with oneof set to message: %v", err)
2108         }
2109         if len(b) != 20 { // msg tag/wire (1) + msg len (1) + msg (1 + 1 + 16)
2110                 t.Errorf("Incorrect marshal of message with oneof set to message: %v", b)
2111         }
2112         m.Reset()
2113         if err := Unmarshal(b, m); err != nil {
2114                 t.Fatalf("Unmarshal of message with oneof set to message: %v", err)
2115         }
2116         ss, ok := m.Union.(*Communique_Msg)
2117         if !ok || ss.Msg.GetStringField() != "deep deep string" {
2118                 t.Errorf("After round trip with oneof set to message, Union = %+v", m.Union)
2119         }
2120 }
2121
2122 func TestInefficientPackedBool(t *testing.T) {
2123         // https://github.com/golang/protobuf/issues/76
2124         inp := []byte{
2125                 0x12, 0x02, // 0x12 = 2<<3|2; 2 bytes
2126                 // Usually a bool should take a single byte,
2127                 // but it is permitted to be any varint.
2128                 0xb9, 0x30,
2129         }
2130         if err := Unmarshal(inp, new(MoreRepeated)); err != nil {
2131                 t.Error(err)
2132         }
2133 }
2134
2135 // Benchmarks
2136
2137 func testMsg() *GoTest {
2138         pb := initGoTest(true)
2139         const N = 1000 // Internally the library starts much smaller.
2140         pb.F_Int32Repeated = make([]int32, N)
2141         pb.F_DoubleRepeated = make([]float64, N)
2142         for i := 0; i < N; i++ {
2143                 pb.F_Int32Repeated[i] = int32(i)
2144                 pb.F_DoubleRepeated[i] = float64(i)
2145         }
2146         return pb
2147 }
2148
2149 func bytesMsg() *GoTest {
2150         pb := initGoTest(true)
2151         buf := make([]byte, 4000)
2152         for i := range buf {
2153                 buf[i] = byte(i)
2154         }
2155         pb.F_BytesDefaulted = buf
2156         return pb
2157 }
2158
2159 func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) {
2160         d, _ := marshal(pb)
2161         b.SetBytes(int64(len(d)))
2162         b.ResetTimer()
2163         for i := 0; i < b.N; i++ {
2164                 marshal(pb)
2165         }
2166 }
2167
2168 func benchmarkBufferMarshal(b *testing.B, pb Message) {
2169         p := NewBuffer(nil)
2170         benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
2171                 p.Reset()
2172                 err := p.Marshal(pb0)
2173                 return p.Bytes(), err
2174         })
2175 }
2176
2177 func benchmarkSize(b *testing.B, pb Message) {
2178         benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
2179                 Size(pb)
2180                 return nil, nil
2181         })
2182 }
2183
2184 func newOf(pb Message) Message {
2185         in := reflect.ValueOf(pb)
2186         if in.IsNil() {
2187                 return pb
2188         }
2189         return reflect.New(in.Type().Elem()).Interface().(Message)
2190 }
2191
2192 func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) {
2193         d, _ := Marshal(pb)
2194         b.SetBytes(int64(len(d)))
2195         pbd := newOf(pb)
2196
2197         b.ResetTimer()
2198         for i := 0; i < b.N; i++ {
2199                 unmarshal(d, pbd)
2200         }
2201 }
2202
2203 func benchmarkBufferUnmarshal(b *testing.B, pb Message) {
2204         p := NewBuffer(nil)
2205         benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error {
2206                 p.SetBuf(d)
2207                 return p.Unmarshal(pb0)
2208         })
2209 }
2210
2211 // Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes}
2212
2213 func BenchmarkMarshal(b *testing.B) {
2214         benchmarkMarshal(b, testMsg(), Marshal)
2215 }
2216
2217 func BenchmarkBufferMarshal(b *testing.B) {
2218         benchmarkBufferMarshal(b, testMsg())
2219 }
2220
2221 func BenchmarkSize(b *testing.B) {
2222         benchmarkSize(b, testMsg())
2223 }
2224
2225 func BenchmarkUnmarshal(b *testing.B) {
2226         benchmarkUnmarshal(b, testMsg(), Unmarshal)
2227 }
2228
2229 func BenchmarkBufferUnmarshal(b *testing.B) {
2230         benchmarkBufferUnmarshal(b, testMsg())
2231 }
2232
2233 func BenchmarkMarshalBytes(b *testing.B) {
2234         benchmarkMarshal(b, bytesMsg(), Marshal)
2235 }
2236
2237 func BenchmarkBufferMarshalBytes(b *testing.B) {
2238         benchmarkBufferMarshal(b, bytesMsg())
2239 }
2240
2241 func BenchmarkSizeBytes(b *testing.B) {
2242         benchmarkSize(b, bytesMsg())
2243 }
2244
2245 func BenchmarkUnmarshalBytes(b *testing.B) {
2246         benchmarkUnmarshal(b, bytesMsg(), Unmarshal)
2247 }
2248
2249 func BenchmarkBufferUnmarshalBytes(b *testing.B) {
2250         benchmarkBufferUnmarshal(b, bytesMsg())
2251 }
2252
2253 func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) {
2254         b.StopTimer()
2255         pb := initGoTestField()
2256         skip := &GoSkipTest{
2257                 SkipInt32:   Int32(32),
2258                 SkipFixed32: Uint32(3232),
2259                 SkipFixed64: Uint64(6464),
2260                 SkipString:  String("skipper"),
2261                 Skipgroup: &GoSkipTest_SkipGroup{
2262                         GroupInt32:  Int32(75),
2263                         GroupString: String("wxyz"),
2264                 },
2265         }
2266
2267         pbd := new(GoTestField)
2268         p := NewBuffer(nil)
2269         p.Marshal(pb)
2270         p.Marshal(skip)
2271         p2 := NewBuffer(nil)
2272
2273         b.StartTimer()
2274         for i := 0; i < b.N; i++ {
2275                 p2.SetBuf(p.Bytes())
2276                 p2.Unmarshal(pbd)
2277         }
2278 }