extensions.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. // Go support for Protocol Buffers - Google's data interchange format
  2. //
  3. // Copyright 2010 The Go Authors. 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. * Types and routines for supporting protocol buffer extensions.
  34. */
  35. import (
  36. "errors"
  37. "reflect"
  38. "strconv"
  39. "sync"
  40. )
  41. // ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
  42. var ErrMissingExtension = errors.New("proto: missing extension")
  43. // ExtensionRange represents a range of message extensions for a protocol buffer.
  44. // Used in code generated by the protocol compiler.
  45. type ExtensionRange struct {
  46. Start, End int32 // both inclusive
  47. }
  48. // extendableProto is an interface implemented by any protocol buffer that may be extended.
  49. type extendableProto interface {
  50. Message
  51. ExtensionRangeArray() []ExtensionRange
  52. ExtensionMap() map[int32]Extension
  53. }
  54. var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
  55. // ExtensionDesc represents an extension specification.
  56. // Used in generated code from the protocol compiler.
  57. type ExtensionDesc struct {
  58. ExtendedType Message // nil pointer to the type that is being extended
  59. ExtensionType interface{} // nil pointer to the extension type
  60. Field int32 // field number
  61. Name string // fully-qualified name of extension, for text formatting
  62. Tag string // protobuf tag style
  63. }
  64. func (ed *ExtensionDesc) repeated() bool {
  65. t := reflect.TypeOf(ed.ExtensionType)
  66. return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
  67. }
  68. // Extension represents an extension in a message.
  69. type Extension struct {
  70. // When an extension is stored in a message using SetExtension
  71. // only desc and value are set. When the message is marshaled
  72. // enc will be set to the encoded form of the message.
  73. //
  74. // When a message is unmarshaled and contains extensions, each
  75. // extension will have only enc set. When such an extension is
  76. // accessed using GetExtension (or GetExtensions) desc and value
  77. // will be set.
  78. desc *ExtensionDesc
  79. value interface{}
  80. enc []byte
  81. }
  82. // SetRawExtension is for testing only.
  83. func SetRawExtension(base extendableProto, id int32, b []byte) {
  84. base.ExtensionMap()[id] = Extension{enc: b}
  85. }
  86. // isExtensionField returns true iff the given field number is in an extension range.
  87. func isExtensionField(pb extendableProto, field int32) bool {
  88. for _, er := range pb.ExtensionRangeArray() {
  89. if er.Start <= field && field <= er.End {
  90. return true
  91. }
  92. }
  93. return false
  94. }
  95. // checkExtensionTypes checks that the given extension is valid for pb.
  96. func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
  97. // Check the extended type.
  98. if a, b := reflect.TypeOf(pb), reflect.TypeOf(extension.ExtendedType); a != b {
  99. return errors.New("bad extended type; " + b.String() + " does not extend " + a.String())
  100. }
  101. // Check the range.
  102. if !isExtensionField(pb, extension.Field) {
  103. return errors.New("bad extension number; not in declared ranges")
  104. }
  105. return nil
  106. }
  107. // extPropKey is sufficient to uniquely identify an extension.
  108. type extPropKey struct {
  109. base reflect.Type
  110. field int32
  111. }
  112. var extProp = struct {
  113. sync.RWMutex
  114. m map[extPropKey]*Properties
  115. }{
  116. m: make(map[extPropKey]*Properties),
  117. }
  118. func extensionProperties(ed *ExtensionDesc) *Properties {
  119. key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
  120. extProp.RLock()
  121. if prop, ok := extProp.m[key]; ok {
  122. extProp.RUnlock()
  123. return prop
  124. }
  125. extProp.RUnlock()
  126. extProp.Lock()
  127. defer extProp.Unlock()
  128. // Check again.
  129. if prop, ok := extProp.m[key]; ok {
  130. return prop
  131. }
  132. prop := new(Properties)
  133. prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
  134. extProp.m[key] = prop
  135. return prop
  136. }
  137. // encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m.
  138. func encodeExtensionMap(m map[int32]Extension) error {
  139. for k, e := range m {
  140. if e.value == nil || e.desc == nil {
  141. // Extension is only in its encoded form.
  142. continue
  143. }
  144. // We don't skip extensions that have an encoded form set,
  145. // because the extension value may have been mutated after
  146. // the last time this function was called.
  147. et := reflect.TypeOf(e.desc.ExtensionType)
  148. props := extensionProperties(e.desc)
  149. p := NewBuffer(nil)
  150. // If e.value has type T, the encoder expects a *struct{ X T }.
  151. // Pass a *T with a zero field and hope it all works out.
  152. x := reflect.New(et)
  153. x.Elem().Set(reflect.ValueOf(e.value))
  154. if err := props.enc(p, props, toStructPointer(x)); err != nil {
  155. return err
  156. }
  157. e.enc = p.buf
  158. m[k] = e
  159. }
  160. return nil
  161. }
  162. // HasExtension returns whether the given extension is present in pb.
  163. func HasExtension(pb extendableProto, extension *ExtensionDesc) bool {
  164. // TODO: Check types, field numbers, etc.?
  165. _, ok := pb.ExtensionMap()[extension.Field]
  166. return ok
  167. }
  168. // ClearExtension removes the given extension from pb.
  169. func ClearExtension(pb extendableProto, extension *ExtensionDesc) {
  170. // TODO: Check types, field numbers, etc.?
  171. delete(pb.ExtensionMap(), extension.Field)
  172. }
  173. // GetExtension parses and returns the given extension of pb.
  174. // If the extension is not present it returns ErrMissingExtension.
  175. // If the returned extension is modified, SetExtension must be called
  176. // for the modifications to be reflected in pb.
  177. func GetExtension(pb extendableProto, extension *ExtensionDesc) (interface{}, error) {
  178. if err := checkExtensionTypes(pb, extension); err != nil {
  179. return nil, err
  180. }
  181. e, ok := pb.ExtensionMap()[extension.Field]
  182. if !ok {
  183. return nil, ErrMissingExtension
  184. }
  185. if e.value != nil {
  186. // Already decoded. Check the descriptor, though.
  187. if e.desc != extension {
  188. // This shouldn't happen. If it does, it means that
  189. // GetExtension was called twice with two different
  190. // descriptors with the same field number.
  191. return nil, errors.New("proto: descriptor conflict")
  192. }
  193. return e.value, nil
  194. }
  195. v, err := decodeExtension(e.enc, extension)
  196. if err != nil {
  197. return nil, err
  198. }
  199. // Remember the decoded version and drop the encoded version.
  200. // That way it is safe to mutate what we return.
  201. e.value = v
  202. e.desc = extension
  203. e.enc = nil
  204. return e.value, nil
  205. }
  206. // decodeExtension decodes an extension encoded in b.
  207. func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
  208. o := NewBuffer(b)
  209. t := reflect.TypeOf(extension.ExtensionType)
  210. rep := extension.repeated()
  211. props := extensionProperties(extension)
  212. // t is a pointer to a struct, pointer to basic type or a slice.
  213. // Allocate a "field" to store the pointer/slice itself; the
  214. // pointer/slice will be stored here. We pass
  215. // the address of this field to props.dec.
  216. // This passes a zero field and a *t and lets props.dec
  217. // interpret it as a *struct{ x t }.
  218. value := reflect.New(t).Elem()
  219. for {
  220. // Discard wire type and field number varint. It isn't needed.
  221. if _, err := o.DecodeVarint(); err != nil {
  222. return nil, err
  223. }
  224. if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
  225. return nil, err
  226. }
  227. if !rep || o.index >= len(o.buf) {
  228. break
  229. }
  230. }
  231. return value.Interface(), nil
  232. }
  233. // GetExtensions returns a slice of the extensions present in pb that are also listed in es.
  234. // The returned slice has the same length as es; missing extensions will appear as nil elements.
  235. func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
  236. epb, ok := pb.(extendableProto)
  237. if !ok {
  238. err = errors.New("not an extendable proto")
  239. return
  240. }
  241. extensions = make([]interface{}, len(es))
  242. for i, e := range es {
  243. extensions[i], err = GetExtension(epb, e)
  244. if err != nil {
  245. return
  246. }
  247. }
  248. return
  249. }
  250. // SetExtension sets the specified extension of pb to the specified value.
  251. func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
  252. if err := checkExtensionTypes(pb, extension); err != nil {
  253. return err
  254. }
  255. typ := reflect.TypeOf(extension.ExtensionType)
  256. if typ != reflect.TypeOf(value) {
  257. return errors.New("bad extension value type")
  258. }
  259. pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
  260. return nil
  261. }
  262. // A global registry of extensions.
  263. // The generated code will register the generated descriptors by calling RegisterExtension.
  264. var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
  265. // RegisterExtension is called from the generated code.
  266. func RegisterExtension(desc *ExtensionDesc) {
  267. st := reflect.TypeOf(desc.ExtendedType).Elem()
  268. m := extensionMaps[st]
  269. if m == nil {
  270. m = make(map[int32]*ExtensionDesc)
  271. extensionMaps[st] = m
  272. }
  273. if _, ok := m[desc.Field]; ok {
  274. panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
  275. }
  276. m[desc.Field] = desc
  277. }
  278. // RegisteredExtensions returns a map of the registered extensions of a
  279. // protocol buffer struct, indexed by the extension number.
  280. // The argument pb should be a nil pointer to the struct type.
  281. func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
  282. return extensionMaps[reflect.TypeOf(pb).Elem()]
  283. }