blob: e98508baa9e104507428db69118377f19c3926e0 [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 Tsai08e00302018-11-26 22:32:06 -08005package legacy
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 Tsaie1f8d502018-11-26 18:55:29 -080031var fileDescCache sync.Map // map[*byte]*descriptorpb.FileDescriptorProto
Joe Tsai90fe9962018-10-18 11:06:29 -070032
Damien Neil987d5702019-04-10 11:06:53 -070033// loadFileDesc 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.
Damien Neil987d5702019-04-10 11:06:53 -070039func loadFileDesc(b []byte) *fileDescriptorProto {
Joe Tsai90fe9962018-10-18 11:06:29 -070040 // Fast-path: check whether we already have a cached file descriptor.
Joe Tsaib9365042019-03-19 14:14:29 -070041 if fd, ok := fileDescCache.Load(&b[0]); ok {
Damien Neil987d5702019-04-10 11:06:53 -070042 return fd.(*fileDescriptorProto)
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 }
Damien Neil987d5702019-04-10 11:06:53 -070054 fd := parseFileDescProto(b)
Joe Tsaib9365042019-03-19 14:14:29 -070055 if fd, ok := fileDescCache.LoadOrStore(&b[0], fd); ok {
Damien Neil987d5702019-04-10 11:06:53 -070056 return fd.(*fileDescriptorProto)
Joe Tsaib9365042019-03-19 14:14:29 -070057 }
58 return fd
Joe Tsai90fe9962018-10-18 11:06:29 -070059}