Skip to content

Commit

Permalink
Fix buffer not put back in pool
Browse files Browse the repository at this point in the history
  • Loading branch information
qdm12 committed Nov 18, 2021
1 parent d5166c5 commit 51633c9
Showing 1 changed file with 21 additions and 26 deletions.
47 changes: 21 additions & 26 deletions lib/trie/hash.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,10 @@ func encodeChildsInParallel(children [16]node, buffer *bytes.Buffer) (err error)
type result struct {
index int
buffer *bytes.Buffer
err error
}

resultsCh := make(chan result)
errorCh := make(chan error)

for i, child := range children {
go func(index int, child node) {
Expand All @@ -169,43 +169,38 @@ func encodeChildsInParallel(children [16]node, buffer *bytes.Buffer) (err error)
// data in the select block below.

err := encodeChild(child, buffer)
if err != nil {
errorCh <- err
return
}

resultsCh <- result{
index: index,
buffer: buffer,
err: err,
}
}(i, child)
}

currentIndex := 0
resultBuffers := make([]*bytes.Buffer, len(children))
for range children {
select {
case result := <-resultsCh:
resultBuffers[result.index] = result.buffer

// write as many completed buffers to the result buffer.
for currentIndex < len(children) &&
resultBuffers[currentIndex] != nil {
// note buffer.Write copies the byte slice given as argument
_, writeErr := buffer.Write(resultBuffers[currentIndex].Bytes())
if writeErr != nil && err == nil {
err = writeErr
}

encodingBufferPool.Put(resultBuffers[currentIndex])
resultBuffers[currentIndex] = nil

currentIndex++
}
case newErr := <-errorCh:
if err == nil { // only set the first error we get
err = newErr
result := <-resultsCh
if result.err != nil && err == nil { // only set the first error we get
err = result.err
}

resultBuffers[result.index] = result.buffer

// write as many completed buffers to the result buffer.
for currentIndex < len(children) &&
resultBuffers[currentIndex] != nil {
// note buffer.Write copies the byte slice given as argument
_, writeErr := buffer.Write(resultBuffers[currentIndex].Bytes())
if writeErr != nil && err == nil {
err = writeErr
}

encodingBufferPool.Put(resultBuffers[currentIndex])
resultBuffers[currentIndex] = nil

currentIndex++
}
}

Expand Down

0 comments on commit 51633c9

Please sign in to comment.