From: YenForYang Date: Mon, 13 Sep 2021 12:52:58 +0000 (-0500) Subject: Inlineable reader.Seek and no-lock return for bad whence (#577) X-Git-Tag: v1.32.0~66 X-Git-Url: http://www.git.stargrave.org/?a=commitdiff_plain;h=5332d3e9d45cd13d86d34c362a3059bde46a8d90;p=btrtrc.git Inlineable reader.Seek and no-lock return for bad whence (#577) * 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 --- diff --git a/reader.go b/reader.go index 31ac7b07..53833e37 100644 --- a/reader.go +++ b/reader.go @@ -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 }