From bf0fbf3de3b8e3f37aec9ce13f25e7187b9d05a1 Mon Sep 17 00:00:00 2001
From: Matt Joiner <anacrolix@gmail.com>
Date: Mon, 26 Feb 2024 09:28:05 +1100
Subject: [PATCH] Remove mutex in MSE cipher reader

It has a very noticeable overhead when the race detector is running. It probably has some unattributed performance impact otherwise.
---
 mse/mse.go | 21 ++++-----------------
 1 file changed, 4 insertions(+), 17 deletions(-)

diff --git a/mse/mse.go b/mse/mse.go
index c3a9f3d3..582a451f 100644
--- a/mse/mse.go
+++ b/mse/mse.go
@@ -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
 }
 
-- 
2.51.0