Make replaceShortcodeTokens rewrite the input slice

Currently a `[]byte` copy is returned. In most cases this is the safe thing to do, but we should just modify/grow the slice as needed.

This is faster and consumes less memory:

```
benchmark                             old ns/op     new ns/op     delta
BenchmarkReplaceShortcodeTokens-4     7350          4419          -39.88%

benchmark                             old allocs     new allocs     delta
BenchmarkReplaceShortcodeTokens-4     5              1              -80.00%

benchmark                             old bytes     new bytes     delta
BenchmarkReplaceShortcodeTokens-4     4816          1152          -76.08%
```

This commit is aso a small spring cleaning of duplicated code in the different `PageConvert` methods.

Fixes #1516
This commit is contained in:
Bjørn Erik Pedersen 2015-10-20 20:35:12 +02:00
parent 4ecf56b891
commit b08d9f26ae
4 changed files with 32 additions and 106 deletions

View file

@ -453,30 +453,14 @@ Loop:
}
// replaceShortcodeTokensInsources calls replaceShortcodeTokens for every source given.
func replaceShortcodeTokensInsources(prefix string, replacements map[string]string, sources ...[]byte) (b [][]byte, err error) {
result := make([][]byte, len(sources))
for i, s := range sources {
b, err := replaceShortcodeTokens(s, prefix, replacements)
if err != nil {
return nil, err
}
result[i] = b
}
return result, nil
}
// Replace prefixed shortcode tokens (HUGOSHORTCODE-1, HUGOSHORTCODE-2) with the real content.
// Note: This function will rewrite the input slice.
func replaceShortcodeTokens(source []byte, prefix string, replacements map[string]string) ([]byte, error) {
if len(replacements) == 0 {
return source, nil
}
buff := bp.GetBuffer()
defer bp.PutBuffer(buff)
sourceLen := len(source)
start := 0
@ -507,28 +491,14 @@ func replaceShortcodeTokens(source []byte, prefix string, replacements map[strin
}
}
oldVal := source[j:end]
_, err := buff.Write(source[start:j])
if err != nil {
return nil, errors.New("buff write failed")
}
_, err = buff.Write(newVal)
if err != nil {
return nil, errors.New("buff write failed")
}
start = j + len(oldVal)
// This and other cool slice tricks: https://github.com/golang/go/wiki/SliceTricks
source = append(source[:j], append(newVal, source[end:]...)...)
k = bytes.Index(source[start:], pre)
}
_, err := buff.Write(source[start:])
if err != nil {
return nil, errors.New("buff write failed")
}
bc := make([]byte, buff.Len(), buff.Len())
copy(bc, buff.Bytes())
return bc, nil
return source, nil
}
func getShortcodeTemplate(name string, t tpl.Template) *template.Template {