allocations improvements and tunnel fixes (#1248)
* reduce allocations in tunnel code Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * another allocation fix Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * allocate maps with len if it known Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org> * allocate key for send once Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
This commit is contained in:
@@ -5,7 +5,16 @@ import (
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"io"
|
||||
|
||||
"github.com/oxtoacart/bpool"
|
||||
)
|
||||
|
||||
var (
|
||||
// the local buffer pool
|
||||
// gcmStandardNonceSize from crypto/cipher/gcm.go is 12 bytes
|
||||
// 100 - is max size of pool
|
||||
noncePool = bpool.NewBytePool(100, 12)
|
||||
hashPool = bpool.NewBytePool(1024*32, 32)
|
||||
)
|
||||
|
||||
// hash hahes the data into 32 bytes key and returns it
|
||||
@@ -13,7 +22,10 @@ import (
|
||||
func hash(key string) []byte {
|
||||
hasher := sha256.New()
|
||||
hasher.Write([]byte(key))
|
||||
return hasher.Sum(nil)
|
||||
out := hashPool.Get()
|
||||
defer hashPool.Put(out[:0])
|
||||
out = hasher.Sum(out[:0])
|
||||
return out
|
||||
}
|
||||
|
||||
// Encrypt encrypts data and returns the encrypted data
|
||||
@@ -32,12 +44,13 @@ func Encrypt(data []byte, key string) ([]byte, error) {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// create a new byte array the size of the nonce
|
||||
// get new byte array the size of the nonce from pool
|
||||
// NOTE: we might use smaller nonce size in the future
|
||||
nonce := make([]byte, gcm.NonceSize())
|
||||
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
nonce := noncePool.Get()
|
||||
if _, err = rand.Read(nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer noncePool.Put(nonce)
|
||||
|
||||
// NOTE: we prepend the nonce to the payload
|
||||
// we need to do this as we need the same nonce
|
||||
|
||||
Reference in New Issue
Block a user