Skip to content

Commit

Permalink
add stringBuilder interface to compatible with < go 1.10
Browse files Browse the repository at this point in the history
  • Loading branch information
zhengchun committed Jul 2, 2020
1 parent 070fdf4 commit 0875c03
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
16 changes: 13 additions & 3 deletions func.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,18 @@ import (
"unicode"
)

// Defined an interface of stringBuilder that compatible with
// strings.Builder(go 1.10) and bytes.Buffer(< go 1.10)
type stringBuilder interface {
WriteRune(r rune) (n int, err error)
WriteString(s string) (int, error)
Reset()
Grow(n int)
String() string
}

var builderPool = sync.Pool{New: func() interface{} {
return &strings.Builder{}
return newStringBuilder()
}}

// The XPath function list.
Expand Down Expand Up @@ -357,7 +367,7 @@ func normalizespaceFunc(q query, t iterator) interface{} {
}
m = node.Value()
}
var b = builderPool.Get().(*strings.Builder)
var b = builderPool.Get().(stringBuilder)
b.Grow(len(m))

runeStr := []rune(strings.TrimSpace(m))
Expand Down Expand Up @@ -524,7 +534,7 @@ func notFunc(q query, t iterator) interface{} {
// concat( string1 , string2 [, stringn]* )
func concatFunc(args ...query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
b := builderPool.Get().(*strings.Builder)
b := builderPool.Get().(stringBuilder)
for _, v := range args {
v = functionArgs(v)

Expand Down
9 changes: 8 additions & 1 deletion func_go110.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,15 @@

package xpath

import "math"
import (
"math"
"strings"
)

func round(f float64) int {
return int(math.Round(f))
}

func newStringBuilder() stringBuilder{
return &strings.Builder{}
}
9 changes: 8 additions & 1 deletion func_pre_go110.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

package xpath

import "math"
import (
"bytes"
"math"
)

// math.Round() is supported by Go 1.10+,
// This method just compatible for version <1.10.
Expand All @@ -13,3 +16,7 @@ func round(f float64) int {
}
return int(f + math.Copysign(0.5, f))
}

func newStringBuilder() stringBuilder {
return &bytes.Buffer{}
}

0 comments on commit 0875c03

Please sign in to comment.