blob: ddf33f7b4a7bae5542c8b334839a3a563df6ceba [file] [log] [blame]
Joe Tsai90fe9962018-10-18 11:06:29 -07001// 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
Joe Tsai21ade492019-05-22 13:42:54 -04005package impl
Joe Tsai90fe9962018-10-18 11:06:29 -07006
7import (
8 "bytes"
9 "compress/gzip"
10 "io/ioutil"
11 "sync"
Joe Tsai90fe9962018-10-18 11:06:29 -070012)
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.
22type (
Joe Tsai6dbffb72018-12-04 14:06:19 -080023 enumV1 interface {
Joe Tsai90fe9962018-10-18 11:06:29 -070024 EnumDescriptor() ([]byte, []int)
25 }
Joe Tsai6dbffb72018-12-04 14:06:19 -080026 messageV1 interface {
Joe Tsai90fe9962018-10-18 11:06:29 -070027 Descriptor() ([]byte, []int)
28 }
29)
30
Joe Tsai21ade492019-05-22 13:42:54 -040031var legacyFileDescCache sync.Map // map[*byte]*descriptorpb.FileDescriptorProto
Joe Tsai90fe9962018-10-18 11:06:29 -070032
Joe Tsai21ade492019-05-22 13:42:54 -040033// legacyLoadFileDesc unmarshals b as a compressed FileDescriptorProto message.
Joe Tsai90fe9962018-10-18 11:06:29 -070034//
35// This assumes that b is immutable and that b does not refer to part of a
36// concatenated series of GZIP files (which would require shenanigans that
37// rely on the concatenation properties of both protobufs and GZIP).
38// File descriptors generated by protoc-gen-go do not rely on that property.
Joe Tsai21ade492019-05-22 13:42:54 -040039func legacyLoadFileDesc(b []byte) *legacyFileDescriptorProto {
Joe Tsai90fe9962018-10-18 11:06:29 -070040 // Fast-path: check whether we already have a cached file descriptor.
Joe Tsai21ade492019-05-22 13:42:54 -040041 if fd, ok := legacyFileDescCache.Load(&b[0]); ok {
42 return fd.(*legacyFileDescriptorProto)
Joe Tsai90fe9962018-10-18 11:06:29 -070043 }
44
45 // Slow-path: decompress and unmarshal the file descriptor proto.
Joe Tsai90fe9962018-10-18 11:06:29 -070046 zr, err := gzip.NewReader(bytes.NewReader(b))
47 if err != nil {
48 panic(err)
49 }
50 b, err = ioutil.ReadAll(zr)
51 if err != nil {
52 panic(err)
53 }
Joe Tsai21ade492019-05-22 13:42:54 -040054 fd := legacyParseFileDescProto(b)
55 if fd, ok := legacyFileDescCache.LoadOrStore(&b[0], fd); ok {
56 return fd.(*legacyFileDescriptorProto)
Joe Tsaib9365042019-03-19 14:14:29 -070057 }
58 return fd
Joe Tsai90fe9962018-10-18 11:06:29 -070059}