Reuse buffers for stream cipher

This commit is contained in:
9seconds
2018-07-20 14:49:22 +03:00
parent c8da08ecce
commit 0d0bdd9fde
2 changed files with 27 additions and 3 deletions
+11 -3
View File
@@ -1,6 +1,7 @@
package wrappers package wrappers
import ( import (
"bytes"
"crypto/cipher" "crypto/cipher"
"net" "net"
@@ -28,10 +29,17 @@ func (s *StreamCipher) Read(p []byte) (int, error) {
} }
func (s *StreamCipher) Write(p []byte) (int, error) { func (s *StreamCipher) Write(p []byte) (int, error) {
encrypted := make([]byte, len(p)) buf := streamCipherBufferPool.Get().(*bytes.Buffer)
s.encryptor.XORKeyStream(encrypted, p) defer streamCipherBufferPool.Put(buf)
return s.conn.Write(encrypted) buf.Reset()
buf.Grow(len(p))
buf.Write(p)
data := buf.Bytes()
s.encryptor.XORKeyStream(data, data)
return s.conn.Write(data)
} }
// Logger returns an instance of the logger for this wrapper. // Logger returns an instance of the logger for this wrapper.
+16
View File
@@ -0,0 +1,16 @@
package wrappers
import (
"bytes"
"sync"
)
var streamCipherBufferPool sync.Pool
func init() {
streamCipherBufferPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
}