From 2034c393f958cbd853714557293ea20c1491d879 Mon Sep 17 00:00:00 2001 From: lash Date: Fri, 31 Mar 2023 12:56:11 +0100 Subject: [PATCH] Implement cache size check --- go/state/state.go | 21 +++++++++++++++++++++ go/state/state_test.go | 14 +++++++++++++- go/vm/vm_test.go | 2 -- 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/go/state/state.go b/go/state/state.go index 15fd388..c1665b9 100644 --- a/go/state/state.go +++ b/go/state/state.go @@ -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 +} diff --git a/go/state/state_test.go b/go/state/state_test.go index 7c15f4c..f44ecb4 100644 --- a/go/state/state_test.go +++ b/go/state/state_test.go @@ -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") + } } diff --git a/go/vm/vm_test.go b/go/vm/vm_test.go index 16627c7..dbdfa8f 100644 --- a/go/vm/vm_test.go +++ b/go/vm/vm_test.go @@ -124,6 +124,4 @@ func TestRunMap(t *testing.T) { if r != expect { t.Errorf("Expected %v, got %v", expect, r) } - - }