Implement cache size check

This commit is contained in:
lash 2023-03-31 12:56:11 +01:00
parent 767321fa2c
commit 2034c393f9
Signed by untrusted user who does not match committer: lash
GPG Key ID: 21D2E7BB88C2A746
3 changed files with 34 additions and 3 deletions

View File

@ -1,6 +1,7 @@
package state
import (
"fmt"
)
type State struct {
@ -40,10 +41,30 @@ func(st *State) Enter(input string) {
}
func(st *State) Add(k string, v string) error {
sz := st.checkCapacity(v)
if sz == 0 {
return fmt.Errorf("Cache capacity exceeded %v of %v", st.CacheUseSize + sz, st.CacheSize)
}
fmt.Printf("len %v %v\n", sz, st.CacheUseSize)
st.Cache[len(st.Cache)-1][k] = v
st.CacheUseSize += sz
return nil
}
func(st *State) Get() (map[string]string, error) {
return st.Cache[len(st.Cache)-1], nil
}
func (st *State) Exit() {
}
func(st *State) checkCapacity(v string) uint32 {
sz := uint32(len(v))
if st.CacheSize == 0 {
return sz
}
if st.CacheUseSize + sz > st.CacheSize {
return 0
}
return sz
}

View File

@ -34,6 +34,18 @@ func TestNewStateCache(t *testing.T) {
func TestStateCacheUse(t *testing.T) {
st := NewState(17, 0)
st = st.WithCacheSize(10)
st.Enter("foo")
st.Add("bar", "baz")
err := st.Add("bar", "baz")
if err != nil {
t.Error(err)
}
err = st.Add("inky", "pinky")
if err != nil {
t.Error(err)
}
err = st.Add("blinky", "clyde")
if err == nil {
t.Errorf("expected capacity error")
}
}

View File

@ -124,6 +124,4 @@ func TestRunMap(t *testing.T) {
if r != expect {
t.Errorf("Expected %v, got %v", expect, r)
}
}