Skip to content

Commit

Permalink
Merge pull request #53 from libp2p/feat/read-more
Browse files Browse the repository at this point in the history
read as much as we can in one go
  • Loading branch information
vyzo committed May 11, 2019
2 parents 03b91c7 + 05add30 commit 9c275bb
Showing 1 changed file with 31 additions and 8 deletions.
39 changes: 31 additions & 8 deletions stream.go
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 @@ -106,21 +119,31 @@ func (s *Stream) returnBuffers() {
}

func (s *Stream) Read(b []byte) (int, error) {
select {
case <-s.reset:
return 0, streammux.ErrReset
default:
}
if s.extra == nil {
err := s.waitForData(context.Background())
if err != nil {
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 9c275bb

Please sign in to comment.