]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Inlineable reader.Seek and no-lock return for bad whence (#577)
authorYenForYang <YenForYang@users.noreply.github.com>
Mon, 13 Sep 2021 12:52:58 +0000 (07:52 -0500)
committerGitHub <noreply@github.com>
Mon, 13 Sep 2021 12:52:58 +0000 (22:52 +1000)
* 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

reader.go

index 31ac7b07937f2c389af59f06bb895b61d4bef911..53833e37038075d9f0fbef4880eca4418957155e 100644 (file)
--- 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
 }