From 51ed3c8744e54c81d7616fe8e041453a0eaa7548 Mon Sep 17 00:00:00 2001 From: serr Date: Sun, 5 Jan 2025 17:18:30 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B4=D0=BE=D0=B1=D0=B0=D0=B2=D0=B8=D0=BB=20?= =?UTF-8?q?=D1=84=D1=83=D0=BD=D0=BA=D1=86=D0=B8=D1=8E,=20=D0=BA=D0=BE?= =?UTF-8?q?=D1=82=D0=BE=D1=80=D0=B0=D1=8F=20=D0=B2=D0=BE=D0=B7=D0=B2=D1=80?= =?UTF-8?q?=D0=B0=D1=89=D0=B0=D0=B5=D1=82=20=D1=80=D0=B0=D0=B7=D0=BC=D0=B5?= =?UTF-8?q?=D1=80=20=D0=B2=D1=81=D0=B5=D0=B3=D0=BE=20=D0=BA=D1=8D=D1=88?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- simplecache.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/simplecache.go b/simplecache.go index 944ac86..1d36b47 100644 --- a/simplecache.go +++ b/simplecache.go @@ -2,6 +2,8 @@ package simplecache import ( "errors" + "fmt" + "reflect" "sync" "time" ) @@ -142,6 +144,72 @@ func (c *Cache) List() []KeyItemPair { return items } +// Вернет размер всего кэша в байтах. +func (c *Cache) Size() int { + c.RLock() + defer c.RUnlock() + + size := 0 + for key, item := range c.storage { + size += isize(key) + isize(item.data) + isize(item.destroyTimestamp) + } + + return size +} + +// ПОДДЕРЖИВАЕМЫЕ ТИПЫ: +// Bool + +// Int + +// Int8 + +// Int16 + +// Int32 + +// Int64 + +// Uint + +// Uint8 + +// Uint16 + +// Uint32 + +// Uint64 + +// Uintptr + +// Float32 + +// Float64 + +// Complex64 + +// Complex128 + +// Array + +// Func + +// Map + +// Slice + +// String + +// Struct +func isize(i interface{}) int { + if i == nil { + return 0 + } + val := reflect.ValueOf(i) + kind := val.Kind() + fmt.Println("val =", val, "kind =", kind) + size := 0 + switch kind { + case reflect.Slice, reflect.Array, reflect.String: + len := val.Len() + for i := 0; i < len; i++ { + size += isize(val.Index(i).Interface()) + } + return size + case reflect.Map: + for _, key := range val.MapKeys() { + size += isize(key.Interface()) + isize(val.MapIndex(key).Interface()) + } + return size + case reflect.Struct: + for i := 0; i < val.NumField(); i++ { + size += isize(val.Field(i).Interface()) + } + return size + default: + return int(reflect.TypeOf(i).Size()) + } +} + // Возвращает данные элемента кэша. func (i *Item) Data() interface{} { return i.data