internal/impl: call Marshal/Unmarshal methods on legacy types

Call the Marshal or Unmarshal method on legacy messages implementing
protoV1.Marshaler or protoV2.Unmarshaler.

We do this in the impl package by creating an appropriate function in
the protoiface.Methods struct for legacy messages.

In proto.MarshalAppend, return the bytes provided by the fast-path
marshal function even when the returned error is non-nil.

Fixes golang/protobuf#955

Change-Id: I36924af9ff959a946c43f2295ef3202216e81b32
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/197357
Reviewed-by: Joe Tsai <joetsai@google.com>
diff --git a/internal/impl/legacy_message.go b/internal/impl/legacy_message.go
index de03ee6..703e865 100644
--- a/internal/impl/legacy_message.go
+++ b/internal/impl/legacy_message.go
@@ -16,6 +16,7 @@
 	"google.golang.org/protobuf/internal/strs"
 	"google.golang.org/protobuf/reflect/protoreflect"
 	pref "google.golang.org/protobuf/reflect/protoreflect"
+	piface "google.golang.org/protobuf/runtime/protoiface"
 )
 
 // legacyWrapMessage wraps v as a protoreflect.ProtoMessage,
@@ -41,6 +42,34 @@
 		Desc:          legacyLoadMessageDesc(t, name),
 		GoReflectType: t,
 	}
+
+	v := reflect.Zero(t).Interface()
+	type marshaler interface {
+		Marshal() ([]byte, error)
+	}
+	if _, ok := v.(marshaler); ok {
+		mi.methods.MarshalAppend = func(b []byte, m pref.Message, _ piface.MarshalOptions) ([]byte, error) {
+			out, err := m.Interface().(unwrapper).protoUnwrap().(marshaler).Marshal()
+			if b != nil {
+				out = append(b, out...)
+			}
+			return out, err
+		}
+		mi.methods.Size = func(m pref.Message, _ piface.MarshalOptions) int {
+			// This is not at all efficient.
+			b, _ := m.Interface().(unwrapper).protoUnwrap().(marshaler).Marshal()
+			return len(b)
+		}
+	}
+	type unmarshaler interface {
+		Unmarshal([]byte) error
+	}
+	if _, ok := v.(unmarshaler); ok {
+		mi.methods.Unmarshal = func(b []byte, m pref.Message, _ piface.UnmarshalOptions) error {
+			return m.Interface().(unwrapper).protoUnwrap().(unmarshaler).Unmarshal(b)
+		}
+	}
+
 	if mi, ok := legacyMessageTypeCache.LoadOrStore(t, mi); ok {
 		return mi.(*MessageInfo)
 	}