encode.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. package proto
  32. /*
  33. * Routines for encoding data into the wire format for protocol buffers.
  34. */
  35. import (
  36. "errors"
  37. "fmt"
  38. "reflect"
  39. )
  40. // RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
  41. // Marshal reports this when a required field is not initialized.
  42. // Unmarshal reports this when a required field is missing from the wire data.
  43. type RequiredNotSetError struct {
  44. field string
  45. }
  46. func (e *RequiredNotSetError) Error() string {
  47. if e.field == "" {
  48. return fmt.Sprintf("proto: required field not set")
  49. }
  50. return fmt.Sprintf("proto: required field %q not set", e.field)
  51. }
  52. var (
  53. // errRepeatedHasNil is the error returned if Marshal is called with
  54. // a struct with a repeated field containing a nil element.
  55. errRepeatedHasNil = errors.New("proto: repeated field has nil element")
  56. // errOneofHasNil is the error returned if Marshal is called with
  57. // a struct with a oneof field containing a nil element.
  58. errOneofHasNil = errors.New("proto: oneof field has nil value")
  59. // ErrNil is the error returned if Marshal is called with nil.
  60. ErrNil = errors.New("proto: Marshal called with nil")
  61. // ErrTooLarge is the error returned if Marshal is called with a
  62. // message that encodes to >2GB.
  63. ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
  64. )
  65. // The fundamental encoders that put bytes on the wire.
  66. // Those that take integer types all accept uint64 and are
  67. // therefore of type valueEncoder.
  68. const maxVarintBytes = 10 // maximum length of a varint
  69. // EncodeVarint returns the varint encoding of x.
  70. // This is the format for the
  71. // int32, int64, uint32, uint64, bool, and enum
  72. // protocol buffer types.
  73. // Not used by the package itself, but helpful to clients
  74. // wishing to use the same encoding.
  75. func EncodeVarint(x uint64) []byte {
  76. var buf [maxVarintBytes]byte
  77. var n int
  78. for n = 0; x > 127; n++ {
  79. buf[n] = 0x80 | uint8(x&0x7F)
  80. x >>= 7
  81. }
  82. buf[n] = uint8(x)
  83. n++
  84. return buf[0:n]
  85. }
  86. // EncodeVarint writes a varint-encoded integer to the Buffer.
  87. // This is the format for the
  88. // int32, int64, uint32, uint64, bool, and enum
  89. // protocol buffer types.
  90. func (p *Buffer) EncodeVarint(x uint64) error {
  91. for x >= 1<<7 {
  92. p.buf = append(p.buf, uint8(x&0x7f|0x80))
  93. x >>= 7
  94. }
  95. p.buf = append(p.buf, uint8(x))
  96. return nil
  97. }
  98. // SizeVarint returns the varint encoding size of an integer.
  99. func SizeVarint(x uint64) int {
  100. switch {
  101. case x < 1<<7:
  102. return 1
  103. case x < 1<<14:
  104. return 2
  105. case x < 1<<21:
  106. return 3
  107. case x < 1<<28:
  108. return 4
  109. case x < 1<<35:
  110. return 5
  111. case x < 1<<42:
  112. return 6
  113. case x < 1<<49:
  114. return 7
  115. case x < 1<<56:
  116. return 8
  117. case x < 1<<63:
  118. return 9
  119. }
  120. return 10
  121. }
  122. // EncodeFixed64 writes a 64-bit integer to the Buffer.
  123. // This is the format for the
  124. // fixed64, sfixed64, and double protocol buffer types.
  125. func (p *Buffer) EncodeFixed64(x uint64) error {
  126. p.buf = append(p.buf,
  127. uint8(x),
  128. uint8(x>>8),
  129. uint8(x>>16),
  130. uint8(x>>24),
  131. uint8(x>>32),
  132. uint8(x>>40),
  133. uint8(x>>48),
  134. uint8(x>>56))
  135. return nil
  136. }
  137. // EncodeFixed32 writes a 32-bit integer to the Buffer.
  138. // This is the format for the
  139. // fixed32, sfixed32, and float protocol buffer types.
  140. func (p *Buffer) EncodeFixed32(x uint64) error {
  141. p.buf = append(p.buf,
  142. uint8(x),
  143. uint8(x>>8),
  144. uint8(x>>16),
  145. uint8(x>>24))
  146. return nil
  147. }
  148. // EncodeZigzag64 writes a zigzag-encoded 64-bit integer
  149. // to the Buffer.
  150. // This is the format used for the sint64 protocol buffer type.
  151. func (p *Buffer) EncodeZigzag64(x uint64) error {
  152. // use signed number to get arithmetic right shift.
  153. return p.EncodeVarint(uint64((x << 1) ^ uint64((int64(x) >> 63))))
  154. }
  155. // EncodeZigzag32 writes a zigzag-encoded 32-bit integer
  156. // to the Buffer.
  157. // This is the format used for the sint32 protocol buffer type.
  158. func (p *Buffer) EncodeZigzag32(x uint64) error {
  159. // use signed number to get arithmetic right shift.
  160. return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
  161. }
  162. // EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
  163. // This is the format used for the bytes protocol buffer
  164. // type and for embedded messages.
  165. func (p *Buffer) EncodeRawBytes(b []byte) error {
  166. p.EncodeVarint(uint64(len(b)))
  167. p.buf = append(p.buf, b...)
  168. return nil
  169. }
  170. // EncodeStringBytes writes an encoded string to the Buffer.
  171. // This is the format used for the proto2 string type.
  172. func (p *Buffer) EncodeStringBytes(s string) error {
  173. p.EncodeVarint(uint64(len(s)))
  174. p.buf = append(p.buf, s...)
  175. return nil
  176. }
  177. // Marshaler is the interface representing objects that can marshal themselves.
  178. type Marshaler interface {
  179. Marshal() ([]byte, error)
  180. }
  181. // EncodeMessage writes the protocol buffer to the Buffer,
  182. // prefixed by a varint-encoded length.
  183. func (p *Buffer) EncodeMessage(pb Message) error {
  184. siz := Size(pb)
  185. p.EncodeVarint(uint64(siz))
  186. return p.Marshal(pb)
  187. }
  188. // All protocol buffer fields are nillable, but be careful.
  189. func isNil(v reflect.Value) bool {
  190. switch v.Kind() {
  191. case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  192. return v.IsNil()
  193. }
  194. return false
  195. }