1
0
mirror of https://github.com/json-iterator/go.git synced 2025-06-15 22:50:24 +02:00

array lazy iterator

This commit is contained in:
Tao Wen
2017-01-24 22:47:56 +08:00
parent 8656482625
commit fa165c684f
4 changed files with 75 additions and 0 deletions

View File

@ -125,3 +125,59 @@ func (any *arrayLazyAny) Size() int {
any.fillCache()
return len(any.cache)
}
func (any *arrayLazyAny) IterateArray() (func() (Any, bool), bool) {
remaining := any.remaining
if len(remaining) == len(any.buf) {
iter := any.parse()
iter.head++
c := iter.nextToken()
if c != ']' {
iter.unreadByte()
v := iter.readAny(iter)
any.cache = append(any.cache, v)
remaining = iter.buf[iter.head:]
any.remaining = remaining
} else {
remaining = nil
any.remaining = nil
return nil, false
}
}
if len(any.cache) == 0 {
return nil, false
}
arr := any.cache
nextValue := arr[0]
i := 1
return func() (Any, bool) {
value := nextValue
if i < len(arr) {
// read from cache
nextValue = arr[i]
i++
return value, true
} else {
// read from buffer
iter := any.iter
if iter == nil {
iter = NewIterator()
any.iter = iter
}
iter.ResetBytes(remaining)
c := iter.nextToken()
if c == ',' {
nextValue = iter.readAny(iter)
any.cache = append(any.cache, nextValue)
remaining = iter.buf[iter.head:]
any.remaining = remaining
return value, true
} else {
remaining = nil
any.remaining = nil
return value, false
}
}
}, true
}