internal/impl: move legacy files into impl

The internal/legacy package was originally separated out from internal/impl
to avoid a cyclic dependency on descriptor proto. However, the dependency
that legacy has on descriptor has long been dropped such that we can
now merge the two packages together again.

All legacy related logic are in a file with a legacy prefix.

Change-Id: I2424fc0f50721696ad06fa7cebb9bdd0babea13c
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/178542
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/internal/impl/legacy_file.go b/internal/impl/legacy_file.go
new file mode 100644
index 0000000..ddf33f7
--- /dev/null
+++ b/internal/impl/legacy_file.go
@@ -0,0 +1,59 @@
+// Copyright 2018 The Go Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style
+// license that can be found in the LICENSE file.
+
+package impl
+
+import (
+	"bytes"
+	"compress/gzip"
+	"io/ioutil"
+	"sync"
+)
+
+// Every enum and message type generated by protoc-gen-go since commit 2fc053c5
+// on February 25th, 2016 has had a method to get the raw descriptor.
+// Types that were not generated by protoc-gen-go or were generated prior
+// to that version are not supported.
+//
+// The []byte returned is the encoded form of a FileDescriptorProto message
+// compressed using GZIP. The []int is the path from the top-level file
+// to the specific message or enum declaration.
+type (
+	enumV1 interface {
+		EnumDescriptor() ([]byte, []int)
+	}
+	messageV1 interface {
+		Descriptor() ([]byte, []int)
+	}
+)
+
+var legacyFileDescCache sync.Map // map[*byte]*descriptorpb.FileDescriptorProto
+
+// legacyLoadFileDesc unmarshals b as a compressed FileDescriptorProto message.
+//
+// This assumes that b is immutable and that b does not refer to part of a
+// concatenated series of GZIP files (which would require shenanigans that
+// rely on the concatenation properties of both protobufs and GZIP).
+// File descriptors generated by protoc-gen-go do not rely on that property.
+func legacyLoadFileDesc(b []byte) *legacyFileDescriptorProto {
+	// Fast-path: check whether we already have a cached file descriptor.
+	if fd, ok := legacyFileDescCache.Load(&b[0]); ok {
+		return fd.(*legacyFileDescriptorProto)
+	}
+
+	// Slow-path: decompress and unmarshal the file descriptor proto.
+	zr, err := gzip.NewReader(bytes.NewReader(b))
+	if err != nil {
+		panic(err)
+	}
+	b, err = ioutil.ReadAll(zr)
+	if err != nil {
+		panic(err)
+	}
+	fd := legacyParseFileDescProto(b)
+	if fd, ok := legacyFileDescCache.LoadOrStore(&b[0], fd); ok {
+		return fd.(*legacyFileDescriptorProto)
+	}
+	return fd
+}