Skip to content

Commit

Permalink
Remove mutex in MSE cipher reader
Browse files Browse the repository at this point in the history
It has a very noticeable overhead when the race detector is running. It probably has some unattributed performance impact otherwise.
  • Loading branch information
anacrolix committed Feb 26, 2024
1 parent 3ad279e commit bf0fbf3
Showing 1 changed file with 4 additions and 17 deletions.
21 changes: 4 additions & 17 deletions mse/mse.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,28 +87,15 @@ func newEncrypt(initer bool, s, skey []byte) (c *rc4.Cipher) {
type cipherReader struct {
c *rc4.Cipher
r io.Reader
mu sync.Mutex
be []byte
}

func (cr *cipherReader) Read(b []byte) (n int, err error) {
var be []byte
cr.mu.Lock()
if len(cr.be) >= len(b) {
be = cr.be
cr.be = nil
cr.mu.Unlock()
} else {
cr.mu.Unlock()
be = make([]byte, len(b))
}
n, err = cr.r.Read(be[:len(b)])
cr.c.XORKeyStream(b[:n], be[:n])
cr.mu.Lock()
if len(be) > len(cr.be) {
cr.be = be
if cap(cr.be) < len(b) {
cr.be = make([]byte, len(b))
}
cr.mu.Unlock()
n, err = cr.r.Read(cr.be[:len(b)])
cr.c.XORKeyStream(b[:n], cr.be[:n])
return
}

Expand Down

0 comments on commit bf0fbf3

Please sign in to comment.