Added Async Cache in pkg cache with Get and Set methods
This commit is contained in:
parent
46f4078530
commit
93defdbef6
|
@ -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
|
||||
}
|
||||
}
|
|
@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue