legacy_file.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package impl
  5. import (
  6. "bytes"
  7. "compress/gzip"
  8. "io/ioutil"
  9. "sync"
  10. "google.golang.org/protobuf/internal/filedesc"
  11. "google.golang.org/protobuf/reflect/protoreflect"
  12. "google.golang.org/protobuf/reflect/protoregistry"
  13. )
  14. // Every enum and message type generated by protoc-gen-go since commit 2fc053c5
  15. // on February 25th, 2016 has had a method to get the raw descriptor.
  16. // Types that were not generated by protoc-gen-go or were generated prior
  17. // to that version are not supported.
  18. //
  19. // The []byte returned is the encoded form of a FileDescriptorProto message
  20. // compressed using GZIP. The []int is the path from the top-level file
  21. // to the specific message or enum declaration.
  22. type (
  23. enumV1 interface {
  24. EnumDescriptor() ([]byte, []int)
  25. }
  26. messageV1 interface {
  27. Descriptor() ([]byte, []int)
  28. }
  29. )
  30. var legacyFileDescCache sync.Map // map[*byte]protoreflect.FileDescriptor
  31. // legacyLoadFileDesc unmarshals b as a compressed FileDescriptorProto message.
  32. //
  33. // This assumes that b is immutable and that b does not refer to part of a
  34. // concatenated series of GZIP files (which would require shenanigans that
  35. // rely on the concatenation properties of both protobufs and GZIP).
  36. // File descriptors generated by protoc-gen-go do not rely on that property.
  37. func legacyLoadFileDesc(b []byte) protoreflect.FileDescriptor {
  38. // Fast-path: check whether we already have a cached file descriptor.
  39. if fd, ok := legacyFileDescCache.Load(&b[0]); ok {
  40. return fd.(protoreflect.FileDescriptor)
  41. }
  42. // Slow-path: decompress and unmarshal the file descriptor proto.
  43. zr, err := gzip.NewReader(bytes.NewReader(b))
  44. if err != nil {
  45. panic(err)
  46. }
  47. b2, err := ioutil.ReadAll(zr)
  48. if err != nil {
  49. panic(err)
  50. }
  51. fd := filedesc.Builder{
  52. RawDescriptor: b2,
  53. FileRegistry: resolverOnly{protoregistry.GlobalFiles}, // do not register back to global registry
  54. }.Build().File
  55. if fd, ok := legacyFileDescCache.LoadOrStore(&b[0], fd); ok {
  56. return fd.(protoreflect.FileDescriptor)
  57. }
  58. return fd
  59. }
  60. type resolverOnly struct {
  61. *protoregistry.Files
  62. }
  63. func (resolverOnly) Register(...protoreflect.FileDescriptor) error { return nil }