Skip to content

Commit

Permalink
Eliminate tmp buffer from packTxtString (#1429)
Browse files Browse the repository at this point in the history
This allocation and the copy of s are both pointless.
  • Loading branch information
tmthrgd authored Mar 12, 2023
1 parent 85afa11 commit b69c3a2
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 20 deletions.
27 changes: 11 additions & 16 deletions msg.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,7 +448,7 @@ Loop:
return string(s), off1, nil
}

func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
func packTxt(txt []string, msg []byte, offset int) (int, error) {
if len(txt) == 0 {
if offset >= len(msg) {
return offset, ErrBuf
Expand All @@ -458,43 +458,38 @@ func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
}
var err error
for _, s := range txt {
if len(s) > len(tmp) {
return offset, ErrBuf
}
offset, err = packTxtString(s, msg, offset, tmp)
offset, err = packTxtString(s, msg, offset)
if err != nil {
return offset, err
}
}
return offset, nil
}

func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) {
func packTxtString(s string, msg []byte, offset int) (int, error) {
lenByteOffset := offset
if offset >= len(msg) || len(s) > len(tmp) {
if offset >= len(msg) || len(s) > 256*4+1 /* If all \DDD */ {
return offset, ErrBuf
}
offset++
bs := tmp[:len(s)]
copy(bs, s)
for i := 0; i < len(bs); i++ {
for i := 0; i < len(s); i++ {
if len(msg) <= offset {
return offset, ErrBuf
}
if bs[i] == '\\' {
if s[i] == '\\' {
i++
if i == len(bs) {
if i == len(s) {
break
}
// check for \DDD
if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
msg[offset] = dddToByte(bs[i:])
if i+2 < len(s) && isDigit(s[i]) && isDigit(s[i+1]) && isDigit(s[i+2]) {
msg[offset] = dddStringToByte(s[i:])
i += 2
} else {
msg[offset] = bs[i]
msg[offset] = s[i]
}
} else {
msg[offset] = bs[i]
msg[offset] = s[i]
}
offset++
}
Expand Down
6 changes: 2 additions & 4 deletions msg_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,8 +299,7 @@ func unpackString(msg []byte, off int) (string, int, error) {
}

func packString(s string, msg []byte, off int) (int, error) {
txtTmp := make([]byte, 256*4+1)
off, err := packTxtString(s, msg, off, txtTmp)
off, err := packTxtString(s, msg, off)
if err != nil {
return len(msg), err
}
Expand Down Expand Up @@ -402,8 +401,7 @@ func unpackStringTxt(msg []byte, off int) ([]string, int, error) {
}

func packStringTxt(s []string, msg []byte, off int) (int, error) {
txtTmp := make([]byte, 256*4+1) // If the whole string consists out of \DDD we need this many.
off, err := packTxt(s, msg, off, txtTmp)
off, err := packTxt(s, msg, off)
if err != nil {
return len(msg), err
}
Expand Down

0 comments on commit b69c3a2

Please sign in to comment.