blob: 9218007be35c9447e8e0f7602bf9d10cb4f6e6b5 [file] [log] [blame]
Rob Pikeaaa3a622010-03-20 22:32:34 -07001// Go support for Protocol Buffers - Google's data interchange format
2//
3// Copyright 2010 Google Inc. All rights reserved.
4// http://code.google.com/p/goprotobuf/
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
32package proto
33
34/*
35 * Routines for encoding data into the wire format for protocol buffers.
36 */
37
38import (
39 "bytes"
40 "os"
41 "reflect"
42 "runtime"
43 "unsafe"
44)
45
46// ErrRequiredNotSet is the error returned if Marshal is called with
47// a protocol buffer struct whose required fields have not
Rob Pikec6d8e4a2010-07-28 15:34:32 -070048// all been initialized. It is also the error returned if Unmarshal is
49// called with an encoded protocol buffer that does not include all the
50// required fields.
Rob Pikeaaa3a622010-03-20 22:32:34 -070051var ErrRequiredNotSet = os.NewError("required fields not set")
52
53// ErrRepeatedHasNil is the error returned if Marshal is called with
54// a protocol buffer struct with a repeated field containing a nil element.
55var ErrRepeatedHasNil = os.NewError("repeated field has nil")
56
57// ErrNil is the error returned if Marshal is called with nil.
58var ErrNil = os.NewError("marshal called with nil")
59
60// The fundamental encoders that put bytes on the wire.
61// Those that take integer types all accept uint64 and are
62// therefore of type valueEncoder.
63
64// EncodeVarint returns the varint encoding of x.
65// This is the format for the
66// int32, int64, uint32, uint64, bool, and enum
67// protocol buffer types.
68// Not used by the package itself, but helpful to clients
69// wishing to use the same encoding.
70func EncodeVarint(x uint64) []byte {
71 var buf [16]byte
72 var n int
73 for n = 0; x > 127; n++ {
74 buf[n] = 0x80 | uint8(x&0x7F)
75 x >>= 7
76 }
77 buf[n] = uint8(x)
78 n++
79 return buf[0:n]
80}
81
82// EncodeVarint writes a varint-encoded integer to the Buffer.
83// This is the format for the
84// int32, int64, uint32, uint64, bool, and enum
85// protocol buffer types.
86func (p *Buffer) EncodeVarint(x uint64) os.Error {
87 l := len(p.buf)
88 c := cap(p.buf)
89 if l+10 > c {
90 c += c/2 + 10
91 obuf := make([]byte, c)
92 copy(obuf, p.buf)
93 p.buf = obuf
94 }
95 p.buf = p.buf[0:c]
96
97 for {
98 if x < 1<<7 {
99 break
100 }
101 p.buf[l] = uint8(x&0x7f | 0x80)
102 l++
103 x >>= 7
104 }
105 p.buf[l] = uint8(x)
106 p.buf = p.buf[0 : l+1]
107 return nil
108}
109
110// EncodeFixed64 writes a 64-bit integer to the Buffer.
111// This is the format for the
112// fixed64, sfixed64, and double protocol buffer types.
113func (p *Buffer) EncodeFixed64(x uint64) os.Error {
114 l := len(p.buf)
115 c := cap(p.buf)
116 if l+8 > c {
117 c += c/2 + 8
118 obuf := make([]byte, c)
119 copy(obuf, p.buf)
120 p.buf = obuf
121 }
122 p.buf = p.buf[0 : l+8]
123
124 p.buf[l] = uint8(x)
125 p.buf[l+1] = uint8(x >> 8)
126 p.buf[l+2] = uint8(x >> 16)
127 p.buf[l+3] = uint8(x >> 24)
128 p.buf[l+4] = uint8(x >> 32)
129 p.buf[l+5] = uint8(x >> 40)
130 p.buf[l+6] = uint8(x >> 48)
131 p.buf[l+7] = uint8(x >> 56)
132 return nil
133}
134
135// EncodeFixed32 writes a 32-bit integer to the Buffer.
136// This is the format for the
137// fixed32, sfixed32, and float protocol buffer types.
138func (p *Buffer) EncodeFixed32(x uint64) os.Error {
139 l := len(p.buf)
140 c := cap(p.buf)
141 if l+4 > c {
142 c += c/2 + 4
143 obuf := make([]byte, c)
144 copy(obuf, p.buf)
145 p.buf = obuf
146 }
147 p.buf = p.buf[0 : l+4]
148
149 p.buf[l] = uint8(x)
150 p.buf[l+1] = uint8(x >> 8)
151 p.buf[l+2] = uint8(x >> 16)
152 p.buf[l+3] = uint8(x >> 24)
153 return nil
154}
155
156// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
157// to the Buffer.
158// This is the format used for the sint64 protocol buffer type.
159func (p *Buffer) EncodeZigzag64(x uint64) os.Error {
160 // use signed number to get arithmetic right shift.
161 return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
162}
163
164// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
165// to the Buffer.
166// This is the format used for the sint32 protocol buffer type.
167func (p *Buffer) EncodeZigzag32(x uint64) os.Error {
168 // use signed number to get arithmetic right shift.
169 return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
170}
171
172// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
173// This is the format used for the bytes protocol buffer
174// type and for embedded messages.
175func (p *Buffer) EncodeRawBytes(b []byte) os.Error {
176 lb := len(b)
177 p.EncodeVarint(uint64(lb))
178 p.buf = bytes.Add(p.buf, b)
179 return nil
180}
181
182// EncodeStringBytes writes an encoded string to the Buffer.
183// This is the format used for the proto2 string type.
184func (p *Buffer) EncodeStringBytes(s string) os.Error {
185
186 // this works because strings and slices are the same.
187 y := *(*[]byte)(unsafe.Pointer(&s))
188 p.EncodeRawBytes(y)
189 return nil
190}
191
192// Marshaler is the interface representing objects that can marshal themselves.
193type Marshaler interface {
194 Marshal() ([]byte, os.Error)
195}
196
197// Marshal takes the protocol buffer struct represented by pb
198// and encodes it into the wire format, returning the data.
199func Marshal(pb interface{}) ([]byte, os.Error) {
200 // Can the object marshal itself?
201 if m, ok := pb.(Marshaler); ok {
202 return m.Marshal()
203 }
204 p := NewBuffer(nil)
205 err := p.Marshal(pb)
206 if err != nil {
207 return nil, err
208 }
209 return p.buf, err
210}
211
212// Marshal takes the protocol buffer struct represented by pb
213// and encodes it into the wire format, writing the result to the
214// Buffer.
215func (p *Buffer) Marshal(pb interface{}) os.Error {
216 // Can the object marshal itself?
217 if m, ok := pb.(Marshaler); ok {
218 data, err := m.Marshal()
219 if err != nil {
220 return err
221 }
222 p.buf = bytes.Add(p.buf, data)
223 return nil
224 }
225
226 mstat := runtime.MemStats.Mallocs
227
228 t, b, err := getbase(pb)
229 if err == nil {
230 err = p.enc_struct(t.Elem().(*reflect.StructType), b)
231 }
232
233 mstat = runtime.MemStats.Mallocs - mstat
234 stats.Emalloc += mstat
235 stats.Encode++
236
237 return err
238}
239
240// Individual type encoders.
241
242// Encode a bool.
243func (o *Buffer) enc_bool(p *Properties, base uintptr) os.Error {
244 v := *(**uint8)(unsafe.Pointer(base + p.offset))
245 if v == nil {
246 return ErrNil
247 }
248 x := *v
249 if x != 0 {
250 x = 1
251 }
252 o.buf = bytes.Add(o.buf, p.tagcode)
253 p.valEnc(o, uint64(x))
254 return nil
255}
256
257// Encode an int32.
258func (o *Buffer) enc_int32(p *Properties, base uintptr) os.Error {
259 v := *(**uint32)(unsafe.Pointer(base + p.offset))
260 if v == nil {
261 return ErrNil
262 }
263 x := *v
264 o.buf = bytes.Add(o.buf, p.tagcode)
265 p.valEnc(o, uint64(x))
266 return nil
267}
268
269// Encode an int64.
270func (o *Buffer) enc_int64(p *Properties, base uintptr) os.Error {
271 v := *(**uint64)(unsafe.Pointer(base + p.offset))
272 if v == nil {
273 return ErrNil
274 }
275 x := *v
276 o.buf = bytes.Add(o.buf, p.tagcode)
277 p.valEnc(o, uint64(x))
278 return nil
279}
280
281// Encode a string.
282func (o *Buffer) enc_string(p *Properties, base uintptr) os.Error {
283 v := *(**string)(unsafe.Pointer(base + p.offset))
284 if v == nil {
285 return ErrNil
286 }
287 x := *v
288 o.buf = bytes.Add(o.buf, p.tagcode)
289 o.EncodeStringBytes(x)
290 return nil
291}
292
293// Encode a message struct.
294func (o *Buffer) enc_struct_message(p *Properties, base uintptr) os.Error {
295 // Can the object marshal itself?
296 iv := unsafe.Unreflect(p.stype, unsafe.Pointer(base+p.offset))
297 if m, ok := iv.(Marshaler); ok {
David Symonds03c9d412010-08-26 14:23:18 +1000298 if n, ok := reflect.NewValue(iv).(nillable); ok && n.IsNil() {
299 return ErrNil
300 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700301 data, err := m.Marshal()
302 if err != nil {
303 return err
304 }
305 o.buf = bytes.Add(o.buf, p.tagcode)
306 o.EncodeRawBytes(data)
307 return nil
308 }
309 v := *(**struct{})(unsafe.Pointer(base + p.offset))
310 if v == nil {
311 return ErrNil
312 }
313
314 // need the length before we can write out the message itself,
315 // so marshal into a separate byte buffer first.
316 obuf := o.buf
317 o.buf = o.bufalloc()
318
319 b := uintptr(unsafe.Pointer(v))
320 typ := p.stype.Elem().(*reflect.StructType)
321 err := o.enc_struct(typ, b)
322
323 nbuf := o.buf
324 o.buf = obuf
325 if err != nil {
326 o.buffree(nbuf)
327 return err
328 }
329 o.buf = bytes.Add(o.buf, p.tagcode)
330 o.EncodeRawBytes(nbuf)
331 o.buffree(nbuf)
332 return nil
333}
334
335// Encode a group struct.
336func (o *Buffer) enc_struct_group(p *Properties, base uintptr) os.Error {
337 v := *(**struct{})(unsafe.Pointer(base + p.offset))
338 if v == nil {
339 return ErrNil
340 }
341
342 o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
343 b := uintptr(unsafe.Pointer(v))
344 typ := p.stype.Elem().(*reflect.StructType)
345 err := o.enc_struct(typ, b)
346 if err != nil {
347 return err
348 }
349 o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
350 return nil
351}
352
353// Encode a slice of bools ([]bool).
354func (o *Buffer) enc_slice_bool(p *Properties, base uintptr) os.Error {
355 s := *(*[]uint8)(unsafe.Pointer(base + p.offset))
356 l := len(s)
357 if l == 0 {
358 return ErrNil
359 }
360 for _, x := range s {
361 o.buf = bytes.Add(o.buf, p.tagcode)
362 if x != 0 {
363 x = 1
364 }
365 p.valEnc(o, uint64(x))
366 }
367 return nil
368}
369
370// Encode a slice of bytes ([]byte).
371func (o *Buffer) enc_slice_byte(p *Properties, base uintptr) os.Error {
372 s := *(*[]uint8)(unsafe.Pointer(base + p.offset))
373 // if the field is required, we must send something, even if it's an empty array.
374 if !p.Required {
375 l := len(s)
376 if l == 0 {
377 return ErrNil
378 }
379 // check default
380 if l == len(p.Default) {
381 same := true
382 for i := 0; i < len(p.Default); i++ {
383 if p.Default[i] != s[i] {
384 same = false
385 break
386 }
387 }
388 if same {
389 return ErrNil
390 }
391 }
392 }
393 o.buf = bytes.Add(o.buf, p.tagcode)
394 o.EncodeRawBytes(s)
395 return nil
396}
397
398// Encode a slice of int32s ([]int32).
399func (o *Buffer) enc_slice_int32(p *Properties, base uintptr) os.Error {
400 s := *(*[]uint32)(unsafe.Pointer(base + p.offset))
401 l := len(s)
402 if l == 0 {
403 return ErrNil
404 }
405 for i := 0; i < l; i++ {
406 o.buf = bytes.Add(o.buf, p.tagcode)
407 x := s[i]
408 p.valEnc(o, uint64(x))
409 }
410 return nil
411}
412
413// Encode a slice of int64s ([]int64).
414func (o *Buffer) enc_slice_int64(p *Properties, base uintptr) os.Error {
415 s := *(*[]uint64)(unsafe.Pointer(base + p.offset))
416 l := len(s)
417 if l == 0 {
418 return ErrNil
419 }
420 for i := 0; i < l; i++ {
421 o.buf = bytes.Add(o.buf, p.tagcode)
422 x := s[i]
423 p.valEnc(o, uint64(x))
424 }
425 return nil
426}
427
428// Encode a slice of slice of bytes ([][]byte).
429func (o *Buffer) enc_slice_slice_byte(p *Properties, base uintptr) os.Error {
430 ss := *(*[][]uint8)(unsafe.Pointer(base + p.offset))
431 l := len(ss)
432 if l == 0 {
433 return ErrNil
434 }
435 for i := 0; i < l; i++ {
436 o.buf = bytes.Add(o.buf, p.tagcode)
437 s := ss[i]
438 o.EncodeRawBytes(s)
439 }
440 return nil
441}
442
443// Encode a slice of strings ([]string).
444func (o *Buffer) enc_slice_string(p *Properties, base uintptr) os.Error {
445 ss := *(*[]string)(unsafe.Pointer(base + p.offset))
446 l := len(ss)
447 for i := 0; i < l; i++ {
448 o.buf = bytes.Add(o.buf, p.tagcode)
449 s := ss[i]
450 o.EncodeStringBytes(s)
451 }
452 return nil
453}
454
455// Encode a slice of message structs ([]*struct).
456func (o *Buffer) enc_slice_struct_message(p *Properties, base uintptr) os.Error {
457 s := *(*[]*struct{})(unsafe.Pointer(base + p.offset))
458 l := len(s)
459 typ := p.stype.Elem().(*reflect.StructType)
460
461 for i := 0; i < l; i++ {
462 v := s[i]
463 if v == nil {
464 return ErrRepeatedHasNil
465 }
466
467 // Can the object marshal itself?
468 iv := unsafe.Unreflect(p.stype, unsafe.Pointer(&s[i]))
469 if m, ok := iv.(Marshaler); ok {
David Symonds03c9d412010-08-26 14:23:18 +1000470 if n, ok := reflect.NewValue(iv).(nillable); ok && n.IsNil() {
471 return ErrNil
472 }
Rob Pikeaaa3a622010-03-20 22:32:34 -0700473 data, err := m.Marshal()
474 if err != nil {
475 return err
476 }
477 o.buf = bytes.Add(o.buf, p.tagcode)
478 o.EncodeRawBytes(data)
479 continue
480 }
481
482 obuf := o.buf
483 o.buf = o.bufalloc()
484
485 b := uintptr(unsafe.Pointer(v))
486 err := o.enc_struct(typ, b)
487
488 nbuf := o.buf
489 o.buf = obuf
490 if err != nil {
491 o.buffree(nbuf)
492 if err == ErrNil {
493 return ErrRepeatedHasNil
494 }
495 return err
496 }
497 o.buf = bytes.Add(o.buf, p.tagcode)
498 o.EncodeRawBytes(nbuf)
499
500 o.buffree(nbuf)
501 }
502 return nil
503}
504
505// Encode a slice of group structs ([]*struct).
506func (o *Buffer) enc_slice_struct_group(p *Properties, base uintptr) os.Error {
507 s := *(*[]*struct{})(unsafe.Pointer(base + p.offset))
508 l := len(s)
509 typ := p.stype.Elem().(*reflect.StructType)
510
511 for i := 0; i < l; i++ {
512 v := s[i]
513 if v == nil {
514 return ErrRepeatedHasNil
515 }
516
517 o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
518
519 b := uintptr(unsafe.Pointer(v))
520 err := o.enc_struct(typ, b)
521
522 if err != nil {
523 if err == ErrNil {
524 return ErrRepeatedHasNil
525 }
526 return err
527 }
528
529 o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
530 }
531 return nil
532}
533
534// Encode an extension map.
535func (o *Buffer) enc_map(p *Properties, base uintptr) os.Error {
536 v := *(*map[int32][]byte)(unsafe.Pointer(base + p.offset))
537 for _, b := range v {
538 o.buf = bytes.Add(o.buf, b)
539 }
540 return nil
541}
542
543// Encode a struct.
544func (o *Buffer) enc_struct(t *reflect.StructType, base uintptr) os.Error {
545 prop := GetProperties(t)
546 required := prop.reqCount
547 for _, p := range prop.Prop {
548 if p.enc != nil {
549 err := p.enc(o, p, base)
550 if err != nil {
551 if err != ErrNil {
552 return err
553 }
554 } else if p.Required {
555 required--
556 }
557 }
558 }
559 // See if we encoded all required fields.
560 if required > 0 {
561 return ErrRequiredNotSet
562 }
563
564 return nil
565}