From fc15e3cfe69eb46d21dfb40753bbcffa0ef81c43 Mon Sep 17 00:00:00 2001 From: Dan Laine Date: Mon, 22 Jun 2020 16:35:42 -0400 Subject: [PATCH] prevent potential memory leaks --- database/encdb/db.go | 6 +++++- database/memdb/db.go | 9 ++++++--- database/prefixdb/db.go | 6 +++++- database/rpcdb/db_client.go | 6 +++++- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/database/encdb/db.go b/database/encdb/db.go index fe33fa7..ddf47e0 100644 --- a/database/encdb/db.go +++ b/database/encdb/db.go @@ -17,6 +17,10 @@ import ( "github.com/ava-labs/gecko/utils/hashing" ) +const ( + minBatchSize = 32 +) + // Database encrypts all values that are provided type Database struct { lock sync.RWMutex @@ -201,7 +205,7 @@ func (b *batch) Write() error { // Reset resets the batch for reuse. func (b *batch) Reset() { - b.writes = b.writes[:0] + b.writes = make([]keyValue, 0, minBatchSize) b.Batch.Reset() } diff --git a/database/memdb/db.go b/database/memdb/db.go index de0cae3..5bbd3a2 100644 --- a/database/memdb/db.go +++ b/database/memdb/db.go @@ -13,8 +13,11 @@ import ( "github.com/ava-labs/gecko/utils" ) -// DefaultSize is the default initial size of the memory database -const DefaultSize = 1 << 10 +const ( + // DefaultSize is the default initial size of the memory database + DefaultSize = 1 << 10 + minBatchSize = 32 +) // Database is an ephemeral key-value store that implements the Database // interface. @@ -191,7 +194,7 @@ func (b *batch) Write() error { // Reset implements the Batch interface func (b *batch) Reset() { - b.writes = b.writes[:0] + b.writes = make([]keyValue, 0, minBatchSize) b.size = 0 } diff --git a/database/prefixdb/db.go b/database/prefixdb/db.go index 34bc50d..a413846 100644 --- a/database/prefixdb/db.go +++ b/database/prefixdb/db.go @@ -12,6 +12,10 @@ import ( "github.com/ava-labs/gecko/utils/hashing" ) +const ( + minBatchSize = 32 +) + // Database partitions a database into a sub-database by prefixing all keys with // a unique value. type Database struct { @@ -199,7 +203,7 @@ func (b *batch) Write() error { // Reset resets the batch for reuse. func (b *batch) Reset() { - b.writes = b.writes[:0] + b.writes = make([]keyValue, 0, minBatchSize) b.Batch.Reset() } diff --git a/database/rpcdb/db_client.go b/database/rpcdb/db_client.go index dc3f60b..f1a3abc 100644 --- a/database/rpcdb/db_client.go +++ b/database/rpcdb/db_client.go @@ -14,6 +14,10 @@ import ( "github.com/ava-labs/gecko/utils" ) +const ( + minBatchSize = 32 +) + var ( errClosed = fmt.Sprintf("rpc error: code = Unknown desc = %s", database.ErrClosed) errNotFound = fmt.Sprintf("rpc error: code = Unknown desc = %s", database.ErrNotFound) @@ -180,7 +184,7 @@ func (b *batch) Write() error { } func (b *batch) Reset() { - b.writes = b.writes[:0] + b.writes = make([]keyValue, 0, minBatchSize) b.size = 0 }