encoding: use strs.UnsafeString to avoid duplicated code
The strs.UnsafeString casts a []byte as a string.
This allows us to avoid duplicated functionality.
Change-Id: I9930b94bae35eac0f98c0fa62963b300bc8d7e49
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/185459
Reviewed-by: Herbie Ong <[email protected]>
diff --git a/internal/encoding/json/string.go b/internal/encoding/json/string.go
index b63dd5c..0730ffa 100644
--- a/internal/encoding/json/string.go
+++ b/internal/encoding/json/string.go
@@ -13,6 +13,7 @@
"unicode/utf8"
"google.golang.org/protobuf/internal/errors"
+ "google.golang.org/protobuf/internal/strs"
)
func appendString(out []byte, in string) ([]byte, error) {
@@ -136,18 +137,4 @@
}
return len(s)
}
-
-// indexNeedEscapeInBytes returns the index of the character that needs
-// escaping. If no characters need escaping, this returns the input length.
-// TODO: Remove this duplicate function when https://golang.org/issue/31506 gets
-// resolved.
-func indexNeedEscapeInBytes(b []byte) int {
- for i := 0; i < len(b); {
- r, n := utf8.DecodeRune(b[i:])
- if r < ' ' || r == '\\' || r == '"' || r == utf8.RuneError {
- return i
- }
- i += n
- }
- return len(b)
-}
+func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) }
diff --git a/internal/encoding/text/string.go b/internal/encoding/text/string.go
index 6792e7a..36314ff 100644
--- a/internal/encoding/text/string.go
+++ b/internal/encoding/text/string.go
@@ -16,6 +16,7 @@
"unicode/utf8"
"google.golang.org/protobuf/internal/errors"
+ "google.golang.org/protobuf/internal/strs"
)
func (p *encoder) marshalString(v Value) error {
@@ -225,18 +226,4 @@
}
return len(s)
}
-
-// indexNeedEscapeInBytes returns the index of the character that needs
-// escaping. If no characters need escaping, this returns the input length.
-// TODO: Remove this duplicate function when https://golang.org/issue/31506 gets
-// resolved.
-func indexNeedEscapeInBytes(b []byte) int {
- for i := 0; i < len(b); {
- c, size := utf8.DecodeRune(b[i:])
- if c < ' ' || c == '"' || c == '\'' || c == '\\' || c >= utf8.RuneSelf {
- return i
- }
- i += size
- }
- return len(b)
-}
+func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) }