Skip to content

Commit

Permalink
Inlineable reader.Seek and no-lock return for bad whence (#577)
Browse files Browse the repository at this point in the history
* Inlineable reader.Seek and no-lock return for bad whence

Couldn't find an elegant way to early exit on bad whence. Using a closure could reduce code duplication slightly, but it's overkill for only 3 cases.

Note that returning 0 on an invalid whence is the behavior of `strings.Reader` and `bytes.Reader`.

* Update reader.go
  • Loading branch information
YenForYang authored Sep 13, 2021
1 parent 134eea8 commit 5332d3e
Showing 1 changed file with 18 additions and 23 deletions.
41 changes: 18 additions & 23 deletions reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -265,31 +265,26 @@ func (r *reader) posChanged() {
}

func (r *reader) Seek(off int64, whence int) (newPos int64, err error) {
r.mu.Lock()
defer r.mu.Unlock()
newPos, err = func() (int64, error) {
switch whence {
case io.SeekStart:
return off, err
case io.SeekCurrent:
return r.pos + off, nil
case io.SeekEnd:
return r.length + off, nil
default:
return r.pos, errors.New("bad whence")
}
}()
if err != nil {
return
switch whence {
case io.SeekStart:
newPos = off
r.mu.Lock()
case io.SeekCurrent:
r.mu.Lock()
newPos = r.pos + off
case io.SeekEnd:
newPos = r.length + off
r.mu.Lock()
default:
return 0, errors.New("bad whence")
}
if newPos == r.pos {
return
if newPos != r.pos {
r.reading = false
r.pos = newPos
r.contiguousReadStartPos = newPos
r.posChanged()
}
r.reading = false
r.pos = newPos
r.contiguousReadStartPos = newPos

r.posChanged()
r.mu.Unlock()
return
}

Expand Down

0 comments on commit 5332d3e

Please sign in to comment.