Simplify unpackString (#1012)

This commit is contained in:
Richard Gibson 2019-09-25 01:53:47 -04:00 committed by Miek Gieben
parent e393768b85
commit 9a6f1f2dc9
1 changed files with 17 additions and 18 deletions

View File

@ -269,33 +269,32 @@ func unpackString(msg []byte, off int) (string, int, error) {
if off+l > len(msg) { if off+l > len(msg) {
return "", off, &Error{err: "overflow unpacking txt"} return "", off, &Error{err: "overflow unpacking txt"}
} }
escapedLen := l
for _, b := range msg[off : off+l] {
switch {
case b == '"' || b == '\\':
escapedLen++
case b < ' ' || b > '~': // unprintable
escapedLen += 3 // escapeByte always returns four characters
}
}
if escapedLen == l { // no escaping needed
return string(msg[off : off+l]), off + l, nil
}
var s strings.Builder var s strings.Builder
s.Grow(escapedLen) consumed := 0
for _, b := range msg[off : off+l] { for i, b := range msg[off : off+l] {
switch { switch {
case b == '"' || b == '\\': case b == '"' || b == '\\':
if consumed == 0 {
s.Grow(l * 2)
}
s.Write(msg[off+consumed : off+i])
s.WriteByte('\\') s.WriteByte('\\')
s.WriteByte(b) s.WriteByte(b)
consumed = i + 1
case b < ' ' || b > '~': // unprintable case b < ' ' || b > '~': // unprintable
if consumed == 0 {
s.Grow(l * 2)
}
s.Write(msg[off+consumed : off+i])
s.WriteString(escapeByte(b)) s.WriteString(escapeByte(b))
default: consumed = i + 1
s.WriteByte(b)
} }
} }
off += l if consumed == 0 { // no escaping needed
return s.String(), off, nil return string(msg[off : off+l]), off + l, nil
}
s.Write(msg[off+consumed : off+l])
return s.String(), off + l, nil
} }
func packString(s string, msg []byte, off int) (int, error) { func packString(s string, msg []byte, off int) (int, error) {