encode.go 13 KB

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