Skip to content

Commit

Permalink
mime: Remove an allocation in word decoding.
Browse files Browse the repository at this point in the history
This fixes a TODO in (*WordDecoder).Decode by replacing a call to strings.Split with
simple prefix/suffix checking and some custom slicing.

Benchmark results:

benchmark                    old ns/op     new ns/op     delta
BenchmarkQEncodeWord-8       740           693           -6.35%
BenchmarkQDecodeWord-8       1291          727           -43.69%
BenchmarkQDecodeHeader-8     1194          767           -35.76%

benchmark                    old allocs     new allocs     delta
BenchmarkQEncodeWord-8       1              1              +0.00%
BenchmarkQDecodeWord-8       3              2              -33.33%
BenchmarkQDecodeHeader-8     3              2              -33.33%

benchmark                    old bytes     new bytes     delta
BenchmarkQEncodeWord-8       48            48            +0.00%
BenchmarkQDecodeWord-8       128           48            -62.50%
BenchmarkQDecodeHeader-8     128           48            -62.50%

Change-Id: I2d6844c75ec2e2b79be2e49b7fc4ca320b7e84e5
Reviewed-on: https://go-review.googlesource.com/14432
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
  • Loading branch information
nussjustin authored and bradfitz committed Oct 18, 2015
1 parent db2e73f commit d0c9b40
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions src/mime/encodedword.go
Expand Up @@ -194,20 +194,32 @@ type WordDecoder struct {

// Decode decodes an RFC 2047 encoded-word.
func (d *WordDecoder) Decode(word string) (string, error) {
fields := strings.Split(word, "?") // TODO: remove allocation?
if len(fields) != 5 || fields[0] != "=" || fields[4] != "=" || len(fields[2]) != 1 {
if !strings.HasPrefix(word, "=?") || !strings.HasSuffix(word, "?=") || strings.Count(word, "?") != 4 {
return "", errInvalidWord
}
word = word[2 : len(word)-2]

content, err := decode(fields[2][0], fields[3])
// split delimits the first 2 fields
split := strings.IndexByte(word, '?')
// the field after split must only be one byte
if word[split+2] != '?' {
return "", errInvalidWord
}

// split word "UTF-8?q?ascii" into "UTF-8", 'q', and "ascii"
charset := word[:split]
encoding := word[split+1]
text := word[split+3:]

content, err := decode(encoding, text)
if err != nil {
return "", err
}

buf := getBuffer()
defer putBuffer(buf)

if err := d.convert(buf, fields[1], content); err != nil {
if err := d.convert(buf, charset, content); err != nil {
return "", err
}

Expand Down

0 comments on commit d0c9b40

Please sign in to comment.