Skip to content

Commit be11930

Browse files
authored
Adding config validation when creating new cache. (#299)
1 parent 16df11e commit be11930

File tree

2 files changed

+38
-12
lines changed

2 files changed

+38
-12
lines changed

bigcache.go

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,18 @@ func NewBigCache(config Config) (*BigCache, error) {
4646
}
4747

4848
func newBigCache(config Config, clock clock) (*BigCache, error) {
49-
5049
if !isPowerOfTwo(config.Shards) {
5150
return nil, fmt.Errorf("Shards number must be power of two")
5251
}
52+
if config.MaxEntrySize < 0 {
53+
return nil, fmt.Errorf("MaxEntrySize must be >= 0")
54+
}
55+
if config.MaxEntriesInWindow < 0 {
56+
return nil, fmt.Errorf("MaxEntriesInWindow must be >= 0")
57+
}
58+
if config.HardMaxCacheSize < 0 {
59+
return nil, fmt.Errorf("HardMaxCacheSize must be >= 0")
60+
}
5361

5462
if config.Hasher == nil {
5563
config.Hasher = newDefaultHasher()

bigcache_test.go

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -156,19 +156,37 @@ func TestConstructCacheWithDefaultHasher(t *testing.T) {
156156
assertEqual(t, true, ok)
157157
}
158158

159-
func TestWillReturnErrorOnInvalidNumberOfPartitions(t *testing.T) {
159+
func TestNewBigcacheValidation(t *testing.T) {
160160
t.Parallel()
161161

162-
// given
163-
cache, error := NewBigCache(Config{
164-
Shards: 18,
165-
LifeWindow: 5 * time.Second,
166-
MaxEntriesInWindow: 10,
167-
MaxEntrySize: 256,
168-
})
169-
170-
assertEqual(t, (*BigCache)(nil), cache)
171-
assertEqual(t, "Shards number must be power of two", error.Error())
162+
for _, tc := range []struct {
163+
cfg Config
164+
want string
165+
}{
166+
{
167+
cfg: Config{Shards: 18},
168+
want: "Shards number must be power of two",
169+
},
170+
{
171+
cfg: Config{Shards: 16, MaxEntriesInWindow: -1},
172+
want: "MaxEntriesInWindow must be >= 0",
173+
},
174+
{
175+
cfg: Config{Shards: 16, MaxEntrySize: -1},
176+
want: "MaxEntrySize must be >= 0",
177+
},
178+
{
179+
cfg: Config{Shards: 16, HardMaxCacheSize: -1},
180+
want: "HardMaxCacheSize must be >= 0",
181+
},
182+
} {
183+
t.Run(tc.want, func(t *testing.T) {
184+
cache, error := NewBigCache(tc.cfg)
185+
186+
assertEqual(t, (*BigCache)(nil), cache)
187+
assertEqual(t, tc.want, error.Error())
188+
})
189+
}
172190
}
173191

174192
func TestEntryNotFound(t *testing.T) {

0 commit comments

Comments
 (0)