Skip to content
Permalink
Browse files

Add stream.GetChunk for reading until full or EOF

  • Loading branch information
jonathan-robertson committed Oct 23, 2017
1 parent 95db7eb commit e1f1363bde94ebc03aa31c667427821cae6b16ab
Showing with 31 additions and 0 deletions.
  1. +31 −0 stream/chunk.go
@@ -0,0 +1,31 @@
package stream

import (
"context"
"io"
)

// GetChunk reads from r until chunk has been filled or until EOF is reached
func GetChunk(ctx context.Context, r io.Reader, chunk []byte) (length int, err error) {
singleByte := make([]byte, 1)

// Loop through bytes until chunk fills or EOF is reached
for i := 0; i < len(chunk); i++ {
select {
case <-ctx.Done():
return 0, context.Canceled

default:
if _, err = r.Read(singleByte); err != nil {
return // return even if io.EOF
}

// Write received byte to chunk
// TODO: Is it more effective for us to append bytes and return chunk?
chunk[i] = singleByte[0]
length++
}
}

return
}

0 comments on commit e1f1363

Please sign in to comment.
You can’t perform that action at this time.