2
0
mirror of synced 2025-02-24 06:38:14 +00:00

Try to reduce allocations in cipherReader

This commit is contained in:
Matt Joiner 2017-08-28 17:27:53 +10:00
parent afb83e792b
commit 2454120af8

View File

@ -84,18 +84,33 @@ func newEncrypt(initer bool, s []byte, skey []byte) (c *rc4.Cipher) {
type cipherReader struct { type cipherReader struct {
c *rc4.Cipher c *rc4.Cipher
r io.Reader r io.Reader
mu sync.Mutex
be []byte
} }
func (cr *cipherReader) Read(b []byte) (n int, err error) { func (cr *cipherReader) Read(b []byte) (n int, err error) {
// inefficient to allocate here var be []byte
be := make([]byte, len(b)) cr.mu.Lock()
n, err = cr.r.Read(be) 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.c.XORKeyStream(b[:n], be[:n])
cr.mu.Lock()
if len(be) > len(cr.be) {
cr.be = be
}
cr.mu.Unlock()
return return
} }
func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader { func newCipherReader(c *rc4.Cipher, r io.Reader) io.Reader {
return &cipherReader{c, r} return &cipherReader{c: c, r: r}
} }
type cipherWriter struct { type cipherWriter struct {
@ -371,7 +386,7 @@ func (h *handshake) initerSteps() (ret io.ReadWriter, err error) {
} }
return return
} }
r := &cipherReader{bC, h.conn} r := newCipherReader(bC, h.conn)
var method uint32 var method uint32
err = unmarshal(r, &method, &padLen) err = unmarshal(r, &method, &padLen)
if err != nil { if err != nil {