Skip to content

Commit

Permalink
read as much as we can in one go
Browse files Browse the repository at this point in the history
  • Loading branch information
Stebalien committed May 10, 2019
1 parent dec60e0 commit f30d815
Showing 1 changed file with 26 additions and 8 deletions.
34 changes: 26 additions & 8 deletions stream.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,19 @@ func (s *Stream) Name() string {
return s.name
}

// tries to preload pending data
func (s *Stream) preloadData() {
select {
case read, ok := <-s.dataIn:
if !ok {
return
}
s.extra = read
s.exbuf = read
default:
}
}

func (s *Stream) waitForData(ctx context.Context) error {
s.deadlineLock.Lock()
if !s.rDeadline.IsZero() {
Expand Down Expand Up @@ -112,15 +125,20 @@ func (s *Stream) Read(b []byte) (int, error) {
return 0, err
}
}
n := copy(b, s.extra)
if n < len(s.extra) {
s.extra = s.extra[n:]
} else {
if s.exbuf != nil {
pool.Put(s.exbuf)
n := 0
for s.extra != nil && n < len(b) {
read := copy(b[n:], s.extra)
n += read
if read < len(s.extra) {
s.extra = s.extra[read:]
} else {
if s.exbuf != nil {
pool.Put(s.exbuf)
}
s.extra = nil
s.exbuf = nil
s.preloadData()
}
s.extra = nil
s.exbuf = nil
}
return n, nil
}
Expand Down

0 comments on commit f30d815

Please sign in to comment.