Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for pooling by allowing reuse of a Result object #374

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions gjson.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,7 +293,7 @@ func (t Result) ForEach(iterator func(key, value Result) bool) {
if !ok {
return
}
if t.Indexes != nil {
if len(t.Indexes) > 0 {
if idx < len(t.Indexes) {
value.Index = t.Indexes[idx]
}
Expand Down Expand Up @@ -321,7 +321,7 @@ func (t Result) Map() map[string]Result {
// The result should be a JSON array or object.
func (t Result) Get(path string) Result {
r := Get(t.Raw, path)
if r.Indexes != nil {
if len(r.Indexes) > 0 {
for i := 0; i < len(r.Indexes); i++ {
r.Indexes[i] += t.Index
}
Expand Down Expand Up @@ -447,7 +447,7 @@ func (t Result) arrayOrMap(vc byte, valueize bool) (r arrayOrMapResult) {
}
}
end:
if t.Indexes != nil {
if len(t.Indexes) > 0 {
if len(t.Indexes) != len(r.a) {
for i := 0; i < len(r.a); i++ {
r.a[i].Index = 0
Expand All @@ -469,6 +469,29 @@ end:
// use the Valid function first.
func Parse(json string) Result {
var value Result
value.Parse(json)
return value
}

// Clear for pooling
func (value *Result) Clear() {
value.Type = 0
value.Raw = ""
value.Str = ""
value.Num = 0
value.Index = 0
if value.Indexes != nil {
value.Indexes = value.Indexes[:0]
}
}

// ParseBytes into an existing Result
func (value *Result) ParseBytes(json []byte) {
value.Parse(string(json))
}

// Parse into an existing Result
func (value *Result) Parse(json string) {
i := 0
for ; i < len(json); i++ {
if json[i] == '{' || json[i] == '[' {
Expand Down Expand Up @@ -504,14 +527,14 @@ func Parse(json string) Result {
value.Type = String
value.Raw, value.Str = tostr(json[i:])
default:
return Result{}
value.Clear()
return
}
break
}
if value.Exists() {
value.Index = i
}
return value
}

// ParseBytes parses the json and returns a result.
Expand Down Expand Up @@ -3431,7 +3454,7 @@ func revSquash(json string) string {
// when the Result came from a path that contained a multipath, modifier,
// or a nested query.
func (t Result) Paths(json string) []string {
if t.Indexes == nil {
if len(t.Indexes) == 0 {
return nil
}
paths := make([]string, 0, len(t.Indexes))
Expand Down