extensions_gogo.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. // Protocol Buffers for Go with Gadgets
  2. //
  3. // Copyright (c) 2013, The GoGo Authors. All rights reserved.
  4. // http://github.com/gogo/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. //
  17. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  18. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  19. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  20. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  21. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  22. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  23. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  24. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  25. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  27. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. package proto
  29. import (
  30. "bytes"
  31. "errors"
  32. "fmt"
  33. "io"
  34. "reflect"
  35. "sort"
  36. "strings"
  37. "sync"
  38. )
  39. type extensionsBytes interface {
  40. Message
  41. ExtensionRangeArray() []ExtensionRange
  42. GetExtensions() *[]byte
  43. }
  44. type slowExtensionAdapter struct {
  45. extensionsBytes
  46. }
  47. func (s slowExtensionAdapter) extensionsWrite() map[int32]Extension {
  48. panic("Please report a bug to github.com/gogo/protobuf if you see this message: Writing extensions is not supported for extensions stored in a byte slice field.")
  49. }
  50. func (s slowExtensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
  51. b := s.GetExtensions()
  52. m, err := BytesToExtensionsMap(*b)
  53. if err != nil {
  54. panic(err)
  55. }
  56. return m, notLocker{}
  57. }
  58. func GetBoolExtension(pb Message, extension *ExtensionDesc, ifnotset bool) bool {
  59. if reflect.ValueOf(pb).IsNil() {
  60. return ifnotset
  61. }
  62. value, err := GetExtension(pb, extension)
  63. if err != nil {
  64. return ifnotset
  65. }
  66. if value == nil {
  67. return ifnotset
  68. }
  69. if value.(*bool) == nil {
  70. return ifnotset
  71. }
  72. return *(value.(*bool))
  73. }
  74. func (this *Extension) Equal(that *Extension) bool {
  75. if err := this.Encode(); err != nil {
  76. return false
  77. }
  78. if err := that.Encode(); err != nil {
  79. return false
  80. }
  81. return bytes.Equal(this.enc, that.enc)
  82. }
  83. func (this *Extension) Compare(that *Extension) int {
  84. if err := this.Encode(); err != nil {
  85. return 1
  86. }
  87. if err := that.Encode(); err != nil {
  88. return -1
  89. }
  90. return bytes.Compare(this.enc, that.enc)
  91. }
  92. func SizeOfInternalExtension(m extendableProto) (n int) {
  93. info := getMarshalInfo(reflect.TypeOf(m))
  94. return info.sizeV1Extensions(m.extensionsWrite())
  95. }
  96. type sortableMapElem struct {
  97. field int32
  98. ext Extension
  99. }
  100. func newSortableExtensionsFromMap(m map[int32]Extension) sortableExtensions {
  101. s := make(sortableExtensions, 0, len(m))
  102. for k, v := range m {
  103. s = append(s, &sortableMapElem{field: k, ext: v})
  104. }
  105. return s
  106. }
  107. type sortableExtensions []*sortableMapElem
  108. func (this sortableExtensions) Len() int { return len(this) }
  109. func (this sortableExtensions) Swap(i, j int) { this[i], this[j] = this[j], this[i] }
  110. func (this sortableExtensions) Less(i, j int) bool { return this[i].field < this[j].field }
  111. func (this sortableExtensions) String() string {
  112. sort.Sort(this)
  113. ss := make([]string, len(this))
  114. for i := range this {
  115. ss[i] = fmt.Sprintf("%d: %v", this[i].field, this[i].ext)
  116. }
  117. return "map[" + strings.Join(ss, ",") + "]"
  118. }
  119. func StringFromInternalExtension(m extendableProto) string {
  120. return StringFromExtensionsMap(m.extensionsWrite())
  121. }
  122. func StringFromExtensionsMap(m map[int32]Extension) string {
  123. return newSortableExtensionsFromMap(m).String()
  124. }
  125. func StringFromExtensionsBytes(ext []byte) string {
  126. m, err := BytesToExtensionsMap(ext)
  127. if err != nil {
  128. panic(err)
  129. }
  130. return StringFromExtensionsMap(m)
  131. }
  132. func EncodeInternalExtension(m extendableProto, data []byte) (n int, err error) {
  133. return EncodeExtensionMap(m.extensionsWrite(), data)
  134. }
  135. func EncodeExtensionMap(m map[int32]Extension, data []byte) (n int, err error) {
  136. o := 0
  137. for _, e := range m {
  138. if err := e.Encode(); err != nil {
  139. return 0, err
  140. }
  141. n := copy(data[o:], e.enc)
  142. if n != len(e.enc) {
  143. return 0, io.ErrShortBuffer
  144. }
  145. o += n
  146. }
  147. return o, nil
  148. }
  149. func GetRawExtension(m map[int32]Extension, id int32) ([]byte, error) {
  150. e := m[id]
  151. if err := e.Encode(); err != nil {
  152. return nil, err
  153. }
  154. return e.enc, nil
  155. }
  156. func size(buf []byte, wire int) (int, error) {
  157. switch wire {
  158. case WireVarint:
  159. _, n := DecodeVarint(buf)
  160. return n, nil
  161. case WireFixed64:
  162. return 8, nil
  163. case WireBytes:
  164. v, n := DecodeVarint(buf)
  165. return int(v) + n, nil
  166. case WireFixed32:
  167. return 4, nil
  168. case WireStartGroup:
  169. offset := 0
  170. for {
  171. u, n := DecodeVarint(buf[offset:])
  172. fwire := int(u & 0x7)
  173. offset += n
  174. if fwire == WireEndGroup {
  175. return offset, nil
  176. }
  177. s, err := size(buf[offset:], wire)
  178. if err != nil {
  179. return 0, err
  180. }
  181. offset += s
  182. }
  183. }
  184. return 0, fmt.Errorf("proto: can't get size for unknown wire type %d", wire)
  185. }
  186. func BytesToExtensionsMap(buf []byte) (map[int32]Extension, error) {
  187. m := make(map[int32]Extension)
  188. i := 0
  189. for i < len(buf) {
  190. tag, n := DecodeVarint(buf[i:])
  191. if n <= 0 {
  192. return nil, fmt.Errorf("unable to decode varint")
  193. }
  194. fieldNum := int32(tag >> 3)
  195. wireType := int(tag & 0x7)
  196. l, err := size(buf[i+n:], wireType)
  197. if err != nil {
  198. return nil, err
  199. }
  200. end := i + int(l) + n
  201. m[int32(fieldNum)] = Extension{enc: buf[i:end]}
  202. i = end
  203. }
  204. return m, nil
  205. }
  206. func NewExtension(e []byte) Extension {
  207. ee := Extension{enc: make([]byte, len(e))}
  208. copy(ee.enc, e)
  209. return ee
  210. }
  211. func AppendExtension(e Message, tag int32, buf []byte) {
  212. if ee, eok := e.(extensionsBytes); eok {
  213. ext := ee.GetExtensions()
  214. *ext = append(*ext, buf...)
  215. return
  216. }
  217. if ee, eok := e.(extendableProto); eok {
  218. m := ee.extensionsWrite()
  219. ext := m[int32(tag)] // may be missing
  220. ext.enc = append(ext.enc, buf...)
  221. m[int32(tag)] = ext
  222. }
  223. }
  224. func encodeExtension(extension *ExtensionDesc, value interface{}) ([]byte, error) {
  225. u := getMarshalInfo(reflect.TypeOf(extension.ExtendedType))
  226. ei := u.getExtElemInfo(extension)
  227. v := value
  228. p := toAddrPointer(&v, ei.isptr)
  229. siz := ei.sizer(p, SizeVarint(ei.wiretag))
  230. buf := make([]byte, 0, siz)
  231. return ei.marshaler(buf, p, ei.wiretag, false)
  232. }
  233. func decodeExtensionFromBytes(extension *ExtensionDesc, buf []byte) (interface{}, error) {
  234. o := 0
  235. for o < len(buf) {
  236. tag, n := DecodeVarint((buf)[o:])
  237. fieldNum := int32(tag >> 3)
  238. wireType := int(tag & 0x7)
  239. if o+n > len(buf) {
  240. return nil, fmt.Errorf("unable to decode extension")
  241. }
  242. l, err := size((buf)[o+n:], wireType)
  243. if err != nil {
  244. return nil, err
  245. }
  246. if int32(fieldNum) == extension.Field {
  247. if o+n+l > len(buf) {
  248. return nil, fmt.Errorf("unable to decode extension")
  249. }
  250. v, err := decodeExtension((buf)[o:o+n+l], extension)
  251. if err != nil {
  252. return nil, err
  253. }
  254. return v, nil
  255. }
  256. o += n + l
  257. }
  258. return defaultExtensionValue(extension)
  259. }
  260. func (this *Extension) Encode() error {
  261. if this.enc == nil {
  262. var err error
  263. this.enc, err = encodeExtension(this.desc, this.value)
  264. if err != nil {
  265. return err
  266. }
  267. }
  268. return nil
  269. }
  270. func (this Extension) GoString() string {
  271. if err := this.Encode(); err != nil {
  272. return fmt.Sprintf("error encoding extension: %v", err)
  273. }
  274. return fmt.Sprintf("proto.NewExtension(%#v)", this.enc)
  275. }
  276. func SetUnsafeExtension(pb Message, fieldNum int32, value interface{}) error {
  277. typ := reflect.TypeOf(pb).Elem()
  278. ext, ok := extensionMaps[typ]
  279. if !ok {
  280. return fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String())
  281. }
  282. desc, ok := ext[fieldNum]
  283. if !ok {
  284. return errors.New("proto: bad extension number; not in declared ranges")
  285. }
  286. return SetExtension(pb, desc, value)
  287. }
  288. func GetUnsafeExtension(pb Message, fieldNum int32) (interface{}, error) {
  289. typ := reflect.TypeOf(pb).Elem()
  290. ext, ok := extensionMaps[typ]
  291. if !ok {
  292. return nil, fmt.Errorf("proto: bad extended type; %s is not extendable", typ.String())
  293. }
  294. desc, ok := ext[fieldNum]
  295. if !ok {
  296. return nil, fmt.Errorf("unregistered field number %d", fieldNum)
  297. }
  298. return GetExtension(pb, desc)
  299. }
  300. func NewUnsafeXXX_InternalExtensions(m map[int32]Extension) XXX_InternalExtensions {
  301. x := &XXX_InternalExtensions{
  302. p: new(struct {
  303. mu sync.Mutex
  304. extensionMap map[int32]Extension
  305. }),
  306. }
  307. x.p.extensionMap = m
  308. return *x
  309. }
  310. func GetUnsafeExtensionsMap(extendable Message) map[int32]Extension {
  311. pb := extendable.(extendableProto)
  312. return pb.extensionsWrite()
  313. }
  314. func deleteExtension(pb extensionsBytes, theFieldNum int32, offset int) int {
  315. ext := pb.GetExtensions()
  316. for offset < len(*ext) {
  317. tag, n1 := DecodeVarint((*ext)[offset:])
  318. fieldNum := int32(tag >> 3)
  319. wireType := int(tag & 0x7)
  320. n2, err := size((*ext)[offset+n1:], wireType)
  321. if err != nil {
  322. panic(err)
  323. }
  324. newOffset := offset + n1 + n2
  325. if fieldNum == theFieldNum {
  326. *ext = append((*ext)[:offset], (*ext)[newOffset:]...)
  327. return offset
  328. }
  329. offset = newOffset
  330. }
  331. return -1
  332. }