encoding/textpb: add string fields UTF-8 validation
Change-Id: I15aec2b90efae9366eb496dc221b9e8cacd9d8e6
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/171122
Reviewed-by: Joe Tsai <thebrokentoaster@gmail.com>
diff --git a/encoding/textpb/encode.go b/encoding/textpb/encode.go
index e293143..c706898 100644
--- a/encoding/textpb/encode.go
+++ b/encoding/textpb/encode.go
@@ -7,6 +7,7 @@
import (
"fmt"
"sort"
+ "unicode/utf8"
"github.com/golang/protobuf/v2/internal/encoding/text"
"github.com/golang/protobuf/v2/internal/encoding/wire"
@@ -174,9 +175,18 @@
pref.Sfixed32Kind, pref.Fixed32Kind,
pref.Sfixed64Kind, pref.Fixed64Kind,
pref.FloatKind, pref.DoubleKind,
- pref.StringKind, pref.BytesKind:
+ pref.BytesKind:
return text.ValueOf(val.Interface()), nil
+ case pref.StringKind:
+ s := val.String()
+ if utf8.ValidString(s) {
+ return text.ValueOf(s), nil
+ }
+ var nerr errors.NonFatal
+ nerr.AppendInvalidUTF8(string(fd.FullName()))
+ return text.ValueOf(s), nerr.E
+
case pref.EnumKind:
num := val.Enum()
if desc := fd.EnumType().Values().ByNumber(num); desc != nil {