From 93defdbef6017d9ed41c10645767f27402e5eac0 Mon Sep 17 00:00:00 2001 From: pm-aadit-patil Date: Mon, 4 Jul 2022 13:51:03 +0530 Subject: [PATCH] Added Async Cache in pkg cache with Get and Set methods --- async_cache.go | 59 ++++++++++++++++++++++++++++++++++++++ async_cache_test.go | 69 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 async_cache.go create mode 100644 async_cache_test.go diff --git a/async_cache.go b/async_cache.go new file mode 100644 index 0000000..31d9640 --- /dev/null +++ b/async_cache.go @@ -0,0 +1,59 @@ +package cache + +import ( + "fmt" + "sync" +) + +type KeyState map[string]state + +// type keyState struct { +// ks KeyState +// } + +var ( + m sync.RWMutex +) + +type state int + +const ( + INPROCESS state = iota + DONE + INVALID +) + +func getState(s state) { + fmt.Println("state", s) +} + +// func NewAsyncCache() keyState { +// var ks keyState +// ks = keyState{ks: make(map[string]state) +// } +// return ks +// } + +func (ks KeyState) Set(key string, S state) bool { + getState(S) + if len(ks) == 0 { + ks = make(KeyState) + } + if len(key) > 0 { + m.Lock() + ks[key] = S + m.Unlock() + } else { + return false + } + return true +} + +func (ks KeyState) Get(key string) state { + if len(key) > 0 { + currS := ks[key] + return currS + } else { + return INVALID + } +} diff --git a/async_cache_test.go b/async_cache_test.go new file mode 100644 index 0000000..3c4cdae --- /dev/null +++ b/async_cache_test.go @@ -0,0 +1,69 @@ +package cache + +import ( + "testing" +) + +func TestSet(t *testing.T) { + + type args struct { + key string + S state + } + tests := []struct { + name string + args args + want bool + }{ + { + name: "Default", + args: args{ + key: "prof_123", + S: INPROCESS, + }, + want: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var ks KeyState + if got := ks.Set(tt.args.key, tt.args.S); got != tt.want { + t.Errorf("Set() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestKeyState_Get(t *testing.T) { + type args struct { + key string + } + tests := []struct { + name string + ks KeyState + args args + want state + }{ + { + name: "Default", + ks: func() KeyState { + var ks KeyState + ks.Set("prof_id_123", INPROCESS) + return ks + }(), + args: args{ + key: "prof_123", + }, + want: 0, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var ks KeyState + ks.Set("prof_id_123", INPROCESS) + if got := tt.ks.Get(tt.args.key); got != tt.want { + t.Errorf("KeyState.Get() = %v, want %v", got, tt.want) + } + }) + } +}