|
32 | 32 | SetExpiredHook(f func(context.Context, string)) Gache
|
33 | 33 | SetWithExpire(string, interface{}, time.Duration)
|
34 | 34 | StartExpired(context.Context, time.Duration) Gache
|
| 35 | + Len() int |
35 | 36 | ToMap(context.Context) *sync.Map
|
36 | 37 | ToRawMap(context.Context) map[string]interface{}
|
37 | 38 | Write(context.Context, io.Writer) error
|
|
63 | 64 | expFuncEnabled bool
|
64 | 65 | expGroup singleflight.Group
|
65 | 66 | expire int64
|
| 67 | + l uint64 |
66 | 68 | shards [256]*sync.Map
|
67 | 69 | }
|
68 | 70 |
|
@@ -192,7 +194,7 @@ func ToMap(ctx context.Context) *sync.Map {
|
192 | 194 |
|
193 | 195 | // ToRawMap returns All Cache Key-Value map
|
194 | 196 | func (g *gache) ToRawMap(ctx context.Context) map[string]interface{} {
|
195 |
| - m := make(map[string]interface{}) |
| 197 | + m := make(map[string]interface{}, g.Len()) |
196 | 198 | mu := new(sync.Mutex)
|
197 | 199 | g.Foreach(ctx, func(key string, val interface{}, exp int64) bool {
|
198 | 200 | mu.Lock()
|
@@ -251,6 +253,7 @@ func (g *gache) set(key string, val interface{}, expire int64) {
|
251 | 253 | if expire > 0 {
|
252 | 254 | expire = fastime.UnixNanoNow() + expire
|
253 | 255 | }
|
| 256 | + atomic.AddUint64(&g.l, 1) |
254 | 257 | g.shards[xxhash.Sum64(*(*[]byte)(unsafe.Pointer(&key)))&0xFF].Store(key, value{
|
255 | 258 | expire: expire,
|
256 | 259 | val: val,
|
@@ -279,6 +282,7 @@ func Set(key string, val interface{}) {
|
279 | 282 |
|
280 | 283 | // Delete deletes value from Gache using key
|
281 | 284 | func (g *gache) Delete(key string) {
|
| 285 | + atomic.StoreUint64(&g.l, atomic.LoadUint64(&g.l)-1) |
282 | 286 | g.shards[xxhash.Sum64(*(*[]byte)(unsafe.Pointer(&key)))&0xFF].Delete(key)
|
283 | 287 | }
|
284 | 288 |
|
@@ -358,9 +362,20 @@ func Foreach(ctx context.Context, f func(string, interface{}, int64) bool) Gache
|
358 | 362 | return instance.Foreach(ctx, f)
|
359 | 363 | }
|
360 | 364 |
|
| 365 | +// Len returns stored object length |
| 366 | +func Len() int { |
| 367 | + return instance.Len() |
| 368 | +} |
| 369 | + |
| 370 | +// Len returns stored object length |
| 371 | +func (g *gache) Len() int { |
| 372 | + l := atomic.LoadUint64(&g.l) |
| 373 | + return *(*int)(unsafe.Pointer(&l)) |
| 374 | +} |
| 375 | + |
361 | 376 | // Write writes all cached data to writer
|
362 | 377 | func (g *gache) Write(ctx context.Context, w io.Writer) error {
|
363 |
| - m := make(map[string]value) |
| 378 | + m := make(map[string]value, g.Len()) |
364 | 379 | mu := new(sync.Mutex)
|
365 | 380 | gb := gob.NewEncoder(lz4.NewWriter(w))
|
366 | 381 | g.Foreach(ctx, func(key string, val interface{}, exp int64) bool {
|
|
0 commit comments