cmd/protoc-gen-go: rely on protoimpl for basic helpers

The EnumName, UnmarshalJSONEnum, and CompressGZIP helpers currently live
in v1 protoapi, which would cause all generated messages to depend on v1.
In an effort to break the dependency of v2 on v1, we move these helper
functions to v2 (and re-written to take advantage of protobuf reflection).

These helpers are unfortunate, but we cannot eliminate the functionality
that they implement since they are exposed in the publicly generated API.

Since EnumName does not rely on the enum maps, it removes another dependency
on those variables. Eventually, we can get to the point where these variables
(though declared) are not linked into the binary if the user does not use them.

Also, we rely on the v1 proto package for registration instead of v1 protoapi.
This may re-introduce a cyclic dependency on descriptor proto again in the
future, but the better approach is to just start registering with v2.

Change-Id: Id755585a7a1df14e4a6a2dfa650df221a3c153fb
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/167921
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/internal/impl/export.go b/internal/impl/export.go
index a38390d..6e54939 100644
--- a/internal/impl/export.go
+++ b/internal/impl/export.go
@@ -5,6 +5,8 @@
 package impl
 
 import (
+	"strconv"
+
 	ptype "github.com/golang/protobuf/v2/internal/prototype"
 	pref "github.com/golang/protobuf/v2/reflect/protoreflect"
 )
@@ -35,6 +37,16 @@
 	return legacyWrapper.EnumTypeOf(e)
 }
 
+// EnumStringOf returns the enum value as a string, either as the name if
+// the number is resolvable, or the number formatted as a string.
+func (Export) EnumStringOf(ed pref.EnumDescriptor, n pref.EnumNumber) string {
+	ev := ed.Values().ByNumber(n)
+	if ev != nil {
+		return string(ev.Name())
+	}
+	return strconv.Itoa(int(n))
+}
+
 // MessageOf returns the protoreflect.Message interface over m.
 // If m already implements proto.Message, then it directly calls the
 // ProtoReflect method, otherwise it wraps the v1 message to implement
diff --git a/internal/impl/legact_export_test.go b/internal/impl/legact_export_test.go
new file mode 100644
index 0000000..e1d2c08
--- /dev/null
+++ b/internal/impl/legact_export_test.go
@@ -0,0 +1,41 @@
+// Copyright 2019 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"
+	"math"
+	"strings"
+	"testing"
+)
+
+func TestCompressGZIP(t *testing.T) {
+	tests := []string{
+		"",
+		"a",
+		"ab",
+		"abc",
+		strings.Repeat("a", math.MaxUint16-1),
+		strings.Repeat("b", math.MaxUint16),
+		strings.Repeat("c", math.MaxUint16+1),
+		strings.Repeat("abcdefghijklmnopqrstuvwxyz", math.MaxUint16-13),
+	}
+	for _, want := range tests {
+		rb := bytes.NewReader(Export{}.CompressGZIP([]byte(want)))
+		zr, err := gzip.NewReader(rb)
+		if err != nil {
+			t.Errorf("unexpected gzip.NewReader error: %v", err)
+		}
+		b, err := ioutil.ReadAll(zr)
+		if err != nil {
+			t.Errorf("unexpected ioutil.ReadAll error: %v", err)
+		}
+		if got := string(b); got != want {
+			t.Errorf("output mismatch: got %q, want %q", got, want)
+		}
+	}
+}
diff --git a/internal/impl/legacy_export.go b/internal/impl/legacy_export.go
new file mode 100644
index 0000000..8038333
--- /dev/null
+++ b/internal/impl/legacy_export.go
@@ -0,0 +1,76 @@
+// Copyright 2019 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 (
+	"encoding/binary"
+	"encoding/json"
+	"hash/crc32"
+	"math"
+
+	"github.com/golang/protobuf/v2/internal/errors"
+	pref "github.com/golang/protobuf/v2/reflect/protoreflect"
+)
+
+// These functions exist to support exported APIs in generated protobufs.
+// While these are deprecated, they cannot be removed for compatibility reasons.
+
+// UnmarshalJSONEnum unmarshals an enum from a JSON-encoded input.
+// The input can either be a string representing the enum value by name,
+// or a number representing the enum number itself.
+func (Export) UnmarshalJSONEnum(ed pref.EnumDescriptor, b []byte) (pref.EnumNumber, error) {
+	if b[0] == '"' {
+		var name pref.Name
+		if err := json.Unmarshal(b, &name); err != nil {
+			return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b)
+		}
+		ev := ed.Values().ByName(name)
+		if ev != nil {
+			return 0, errors.New("invalid value for enum %v: %s", ed.FullName(), name)
+		}
+		return ev.Number(), nil
+	} else {
+		var num pref.EnumNumber
+		if err := json.Unmarshal(b, &num); err != nil {
+			return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b)
+		}
+		return num, nil
+	}
+}
+
+// CompressGZIP compresses the input as a GZIP-encoded file.
+// The current implementation does no compression.
+func (Export) CompressGZIP(in []byte) (out []byte) {
+	// RFC 1952, section 2.3.1.
+	var gzipHeader = [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}
+
+	// RFC 1951, section 3.2.4.
+	var blockHeader [5]byte
+	const maxBlockSize = math.MaxUint16
+	numBlocks := 1 + len(in)/maxBlockSize
+
+	// RFC 1952, section 2.3.1.
+	var gzipFooter [8]byte
+	binary.LittleEndian.PutUint32(gzipFooter[0:4], crc32.ChecksumIEEE(in))
+	binary.LittleEndian.PutUint32(gzipFooter[4:8], uint32(len(in)))
+
+	// Encode the input without compression using raw DEFLATE blocks.
+	out = make([]byte, 0, len(gzipHeader)+len(blockHeader)*numBlocks+len(in)+len(gzipFooter))
+	out = append(out, gzipHeader[:]...)
+	for blockHeader[0] == 0 {
+		blockSize := maxBlockSize
+		if blockSize > len(in) {
+			blockHeader[0] = 0x01 // final bit per RFC 1951, section 3.2.3.
+			blockSize = len(in)
+		}
+		binary.LittleEndian.PutUint16(blockHeader[1:3], uint16(blockSize)^0x0000)
+		binary.LittleEndian.PutUint16(blockHeader[3:5], uint16(blockSize)^0xffff)
+		out = append(out, blockHeader[:]...)
+		out = append(out, in[:blockSize]...)
+		in = in[blockSize:]
+	}
+	out = append(out, gzipFooter[:]...)
+	return out
+}