Configurable TextMarshaler for protos.
This also replaces (Marshal|Compact)Text(String?) implementations with
calls to the TextMarshaler methods.
Signed-off-by: David Symonds <dsymonds@golang.org>
diff --git a/proto/text.go b/proto/text.go
index 2336b14..1cbaf86 100644
--- a/proto/text.go
+++ b/proto/text.go
@@ -685,7 +685,14 @@
w.complete = false
}
-func marshalText(w io.Writer, pb Message, compact bool) error {
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+ Compact bool // use compact text format (one line).
+}
+
+// Marshal writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func (m *TextMarshaler) Marshal(w io.Writer, pb Message) error {
val := reflect.ValueOf(pb)
if pb == nil || val.IsNil() {
w.Write([]byte("<nil>"))
@@ -700,7 +707,7 @@
aw := &textWriter{
w: ww,
complete: true,
- compact: compact,
+ compact: m.Compact,
}
if tm, ok := pb.(encoding.TextMarshaler); ok {
@@ -727,25 +734,29 @@
return nil
}
+// Text is the same as Marshal, but returns the string directly.
+func (m *TextMarshaler) Text(pb Message) string {
+ var buf bytes.Buffer
+ m.Marshal(&buf, pb)
+ return buf.String()
+}
+
+var (
+ defaultTextMarshaler = TextMarshaler{}
+ compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// TODO: consider removing some of the Marshal functions below.
+
// MarshalText writes a given protocol buffer in text format.
// The only errors returned are from w.
-func MarshalText(w io.Writer, pb Message) error {
- return marshalText(w, pb, false)
-}
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, false)
- return buf.String()
-}
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, true)
- return buf.String()
-}
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }