lib.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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. /*
  32. The proto package converts data structures to and from the
  33. wire format of protocol buffers. It works in concert with the
  34. Go source code generated for .proto files by the protocol compiler.
  35. A summary of the properties of the protocol buffer interface
  36. for a protocol buffer variable v:
  37. - Names are turned from camel_case to CamelCase for export.
  38. - There are no methods on v to set and get fields; just treat
  39. them as structure fields.
  40. - The zero value for a struct is its correct initialization state.
  41. All desired fields must be set before marshaling.
  42. - A Reset() method will restore a protobuf struct to its zero state.
  43. - Each type T has a method NewT() to create a new instance. It
  44. is equivalent to new(T).
  45. - Non-repeated fields are pointers to the values; nil means unset.
  46. That is, optional or required field int32 f becomes F *int32.
  47. - Repeated fields are slices.
  48. - Helper functions are available to simplify the getting and setting of fields:
  49. foo.String = proto.String("hello") // set field
  50. s := proto.GetString(foo.String) // get field
  51. - Constants are defined to hold the default values of all fields that
  52. have them. They have the form Default_StructName_FieldName.
  53. - Enums are given type names and maps between names to values,
  54. plus a helper function to create values. Enum values are prefixed
  55. with the enum's type name.
  56. - Nested groups and enums have type names prefixed with the name of
  57. the surrounding message type.
  58. - Extensions are given descriptor names that start with E_,
  59. followed by an underscore-delimited list of the nested messages
  60. that contain it (if any) followed by the CamelCased name of the
  61. extension field itself. HasExtension, ClearExtension, GetExtension
  62. and SetExtension are functions for manipulating extensions.
  63. - Marshal and Unmarshal are functions to encode and decode the wire format.
  64. The simplest way to describe this is to see an example.
  65. Given file test.proto, containing
  66. package example;
  67. enum FOO { X = 17; };
  68. message Test {
  69. required string label = 1;
  70. optional int32 type = 2 [default=77];
  71. repeated int64 reps = 3;
  72. optional group OptionalGroup = 4 {
  73. required string RequiredField = 5;
  74. };
  75. }
  76. The resulting file, test.pb.go, is:
  77. package example
  78. import "goprotobuf.googlecode.com/hg/proto"
  79. type FOO int32
  80. const (
  81. FOO_X = 17
  82. )
  83. var FOO_name = map[int32] string {
  84. 17: "X",
  85. }
  86. var FOO_value = map[string] int32 {
  87. "X": 17,
  88. }
  89. func NewFOO(x int32) *FOO {
  90. e := FOO(x)
  91. return &e
  92. }
  93. type Test struct {
  94. Label *string "PB(bytes,1,req,name=label)"
  95. Type *int32 "PB(varint,2,opt,name=type,def=77)"
  96. Reps []int64 "PB(varint,3,rep,name=reps)"
  97. Optionalgroup *Test_OptionalGroup "PB(group,4,opt,name=optionalgroup)"
  98. XXX_unrecognized []byte
  99. }
  100. func (this *Test) Reset() {
  101. *this = Test{}
  102. }
  103. func NewTest() *Test {
  104. return new(Test)
  105. }
  106. const Default_Test_Type int32 = 77
  107. type Test_OptionalGroup struct {
  108. RequiredField *string "PB(bytes,5,req)"
  109. XXX_unrecognized []byte
  110. }
  111. func (this *Test_OptionalGroup) Reset() {
  112. *this = Test_OptionalGroup{}
  113. }
  114. func NewTest_OptionalGroup() *Test_OptionalGroup {
  115. return new(Test_OptionalGroup)
  116. }
  117. func init() {
  118. proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
  119. }
  120. To create and play with a Test object:
  121. package main
  122. import (
  123. "log"
  124. "goprotobuf.googlecode.com/hg/proto"
  125. "./example.pb"
  126. )
  127. func main() {
  128. test := &example.Test {
  129. Label: proto.String("hello"),
  130. Type: proto.Int32(17),
  131. Optionalgroup: &example.Test_OptionalGroup {
  132. RequiredField: proto.String("good bye"),
  133. },
  134. }
  135. data, err := proto.Marshal(test)
  136. if err != nil {
  137. log.Exit("marshaling error:", err)
  138. }
  139. newTest := example.NewTest()
  140. err = proto.Unmarshal(data, newTest)
  141. if err != nil {
  142. log.Exit("unmarshaling error:", err)
  143. }
  144. // Now test and newTest contain the same data.
  145. if proto.GetString(test.Label) != proto.GetString(newTest.Label) {
  146. log.Exit("data mismatch %q %q", proto.GetString(test.Label), proto.GetString(newTest.Label))
  147. }
  148. // etc.
  149. }
  150. */
  151. package proto
  152. import (
  153. "fmt"
  154. "strconv"
  155. )
  156. // Stats records allocation details about the protocol buffer encoders
  157. // and decoders. Useful for tuning the library itself.
  158. type Stats struct {
  159. Emalloc uint64 // mallocs in encode
  160. Dmalloc uint64 // mallocs in decode
  161. Encode uint64 // number of encodes
  162. Decode uint64 // number of decodes
  163. Chit uint64 // number of cache hits
  164. Cmiss uint64 // number of cache misses
  165. }
  166. var stats Stats
  167. // GetStats returns a copy of the global Stats structure.
  168. func GetStats() Stats { return stats }
  169. // A Buffer is a buffer manager for marshaling and unmarshaling
  170. // protocol buffers. It may be reused between invocations to
  171. // reduce memory usage. It is not necessary to use a Buffer;
  172. // the global functions Marshal and Unmarshal create a
  173. // temporary Buffer and are fine for most applications.
  174. type Buffer struct {
  175. buf []byte // encode/decode byte stream
  176. index int // write point
  177. freelist [10][]byte // list of available buffers
  178. nfreelist int // number of free buffers
  179. ptr uintptr // scratch area for pointers
  180. }
  181. // NewBuffer allocates a new Buffer and initializes its internal data to
  182. // the contents of the argument slice.
  183. func NewBuffer(e []byte) *Buffer {
  184. p := new(Buffer)
  185. if e == nil {
  186. e = p.bufalloc()
  187. }
  188. p.buf = e
  189. p.index = 0
  190. return p
  191. }
  192. // Reset resets the Buffer, ready for marshaling a new protocol buffer.
  193. func (p *Buffer) Reset() {
  194. if p.buf == nil {
  195. p.buf = p.bufalloc()
  196. }
  197. p.buf = p.buf[0:0] // for reading/writing
  198. p.index = 0 // for reading
  199. }
  200. // SetBuf replaces the internal buffer with the slice,
  201. // ready for unmarshaling the contents of the slice.
  202. func (p *Buffer) SetBuf(s []byte) {
  203. p.buf = s
  204. p.index = 0
  205. }
  206. // Bytes returns the contents of the Buffer.
  207. func (p *Buffer) Bytes() []byte { return p.buf }
  208. // Allocate a buffer for the Buffer.
  209. func (p *Buffer) bufalloc() []byte {
  210. if p.nfreelist > 0 {
  211. // reuse an old one
  212. p.nfreelist--
  213. s := p.freelist[p.nfreelist]
  214. return s[0:0]
  215. }
  216. // make a new one
  217. s := make([]byte, 0, 16)
  218. return s
  219. }
  220. // Free (and remember in freelist) a byte buffer for the Buffer.
  221. func (p *Buffer) buffree(s []byte) {
  222. if p.nfreelist < len(p.freelist) {
  223. // Take next slot.
  224. p.freelist[p.nfreelist] = s
  225. p.nfreelist++
  226. return
  227. }
  228. // Find the smallest.
  229. besti := -1
  230. bestl := len(s)
  231. for i, b := range p.freelist {
  232. if len(b) < bestl {
  233. besti = i
  234. bestl = len(b)
  235. }
  236. }
  237. // Overwrite the smallest.
  238. if besti >= 0 {
  239. p.freelist[besti] = s
  240. }
  241. }
  242. /*
  243. * Helper routines for simplifying the creation of optional fields of basic type.
  244. */
  245. // Bool is a helper routine that allocates a new bool value
  246. // to store v and returns a pointer to it.
  247. func Bool(v bool) *bool {
  248. p := new(bool)
  249. *p = v
  250. return p
  251. }
  252. // Int32 is a helper routine that allocates a new int32 value
  253. // to store v and returns a pointer to it.
  254. func Int32(v int32) *int32 {
  255. p := new(int32)
  256. *p = v
  257. return p
  258. }
  259. // Int is a helper routine that allocates a new int32 value
  260. // to store v and returns a pointer to it, but unlike Int32
  261. // its argument value is an int.
  262. func Int(v int) *int32 {
  263. p := new(int32)
  264. *p = int32(v)
  265. return p
  266. }
  267. // Int64 is a helper routine that allocates a new int64 value
  268. // to store v and returns a pointer to it.
  269. func Int64(v int64) *int64 {
  270. p := new(int64)
  271. *p = v
  272. return p
  273. }
  274. // Float32 is a helper routine that allocates a new float32 value
  275. // to store v and returns a pointer to it.
  276. func Float32(v float32) *float32 {
  277. p := new(float32)
  278. *p = v
  279. return p
  280. }
  281. // Float64 is a helper routine that allocates a new float64 value
  282. // to store v and returns a pointer to it.
  283. func Float64(v float64) *float64 {
  284. p := new(float64)
  285. *p = v
  286. return p
  287. }
  288. // Uint32 is a helper routine that allocates a new uint32 value
  289. // to store v and returns a pointer to it.
  290. func Uint32(v uint32) *uint32 {
  291. p := new(uint32)
  292. *p = v
  293. return p
  294. }
  295. // Uint64 is a helper routine that allocates a new uint64 value
  296. // to store v and returns a pointer to it.
  297. func Uint64(v uint64) *uint64 {
  298. p := new(uint64)
  299. *p = v
  300. return p
  301. }
  302. // String is a helper routine that allocates a new string value
  303. // to store v and returns a pointer to it.
  304. func String(v string) *string {
  305. p := new(string)
  306. *p = v
  307. return p
  308. }
  309. /*
  310. * Helper routines for simplifying the fetching of optional fields of basic type.
  311. * If the field is missing, they return the zero for the type.
  312. */
  313. // GetBool is a helper routine that returns an optional bool value.
  314. func GetBool(p *bool) bool {
  315. if p == nil {
  316. return false
  317. }
  318. return *p
  319. }
  320. // GetInt32 is a helper routine that returns an optional int32 value.
  321. func GetInt32(p *int32) int32 {
  322. if p == nil {
  323. return 0
  324. }
  325. return *p
  326. }
  327. // GetInt64 is a helper routine that returns an optional int64 value.
  328. func GetInt64(p *int64) int64 {
  329. if p == nil {
  330. return 0
  331. }
  332. return *p
  333. }
  334. // GetFloat32 is a helper routine that returns an optional float32 value.
  335. func GetFloat32(p *float32) float32 {
  336. if p == nil {
  337. return 0
  338. }
  339. return *p
  340. }
  341. // GetFloat64 is a helper routine that returns an optional float64 value.
  342. func GetFloat64(p *float64) float64 {
  343. if p == nil {
  344. return 0
  345. }
  346. return *p
  347. }
  348. // GetUint32 is a helper routine that returns an optional uint32 value.
  349. func GetUint32(p *uint32) uint32 {
  350. if p == nil {
  351. return 0
  352. }
  353. return *p
  354. }
  355. // GetUint64 is a helper routine that returns an optional uint64 value.
  356. func GetUint64(p *uint64) uint64 {
  357. if p == nil {
  358. return 0
  359. }
  360. return *p
  361. }
  362. // GetString is a helper routine that returns an optional string value.
  363. func GetString(p *string) string {
  364. if p == nil {
  365. return ""
  366. }
  367. return *p
  368. }
  369. // EnumName is a helper function to simplify printing protocol buffer enums
  370. // by name. Given an enum map and a value, it returns a useful string.
  371. func EnumName(m map[int32]string, v int32) string {
  372. s, ok := m[v]
  373. if ok {
  374. return s
  375. }
  376. return "unknown_enum_" + strconv.Itoa(int(v))
  377. }
  378. // DebugPrint dumps the encoded data in b in a debugging format with a header
  379. // including the string s. Used in testing but made available for general debugging.
  380. func (o *Buffer) DebugPrint(s string, b []byte) {
  381. var u uint64
  382. obuf := o.buf
  383. index := o.index
  384. o.buf = b
  385. o.index = 0
  386. depth := 0
  387. fmt.Printf("\n--- %s ---\n", s)
  388. out:
  389. for {
  390. for i := 0; i < depth; i++ {
  391. fmt.Print(" ")
  392. }
  393. index := o.index
  394. if index == len(o.buf) {
  395. break
  396. }
  397. op, err := o.DecodeVarint()
  398. if err != nil {
  399. fmt.Printf("%3d: fetching op err %v\n", index, err)
  400. break out
  401. }
  402. tag := op >> 3
  403. wire := op & 7
  404. switch wire {
  405. default:
  406. fmt.Printf("%3d: t=%3d unknown wire=%d\n",
  407. index, tag, wire)
  408. break out
  409. case WireBytes:
  410. var r []byte
  411. r, err = o.DecodeRawBytes(false)
  412. if err != nil {
  413. break out
  414. }
  415. fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
  416. if len(r) <= 6 {
  417. for i := 0; i < len(r); i++ {
  418. fmt.Printf(" %.2x", r[i])
  419. }
  420. } else {
  421. for i := 0; i < 3; i++ {
  422. fmt.Printf(" %.2x", r[i])
  423. }
  424. fmt.Printf(" ..")
  425. for i := len(r) - 3; i < len(r); i++ {
  426. fmt.Printf(" %.2x", r[i])
  427. }
  428. }
  429. fmt.Printf("\n")
  430. case WireFixed32:
  431. u, err = o.DecodeFixed32()
  432. if err != nil {
  433. fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
  434. break out
  435. }
  436. fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
  437. case WireFixed64:
  438. u, err = o.DecodeFixed64()
  439. if err != nil {
  440. fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
  441. break out
  442. }
  443. fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
  444. break
  445. case WireVarint:
  446. u, err = o.DecodeVarint()
  447. if err != nil {
  448. fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
  449. break out
  450. }
  451. fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
  452. case WireStartGroup:
  453. if err != nil {
  454. fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
  455. break out
  456. }
  457. fmt.Printf("%3d: t=%3d start\n", index, tag)
  458. depth++
  459. case WireEndGroup:
  460. depth--
  461. if err != nil {
  462. fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
  463. break out
  464. }
  465. fmt.Printf("%3d: t=%3d end\n", index, tag)
  466. }
  467. }
  468. if depth != 0 {
  469. fmt.Printf("%3d: start-end not balanced %d\n", o.index, depth)
  470. }
  471. fmt.Printf("\n")
  472. o.buf = obuf
  473. o.index = index
  474. }