From ed10574deacf5a27be9572a94c1ae2e39e11ff6c Mon Sep 17 00:00:00 2001 From: Ophestra Date: Fri, 20 Dec 2024 19:05:39 +0900 Subject: [PATCH] state: store join util Signed-off-by: Ophestra --- internal/state/state_test.go | 8 ++++++ internal/state/util.go | 49 ++++++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+) create mode 100644 internal/state/util.go diff --git a/internal/state/state_test.go b/internal/state/state_test.go index 9af438e..b19c64b 100644 --- a/internal/state/state_test.go +++ b/internal/state/state_test.go @@ -94,6 +94,14 @@ func testStore(t *testing.T, s state.Store) { } }) + t.Run("join store", func(t *testing.T) { + if entries, err := state.Join(s); err != nil { + t.Fatalf("Join: error = %v", err) + } else if len(entries) != 3 { + t.Fatalf("Join(s) = %#v", entries) + } + }) + t.Run("clear aid 1", func(t *testing.T) { do(1, func(c state.Cursor) { if err := c.Destroy(tc[insertEntryOtherApp].ID); err != nil { diff --git a/internal/state/util.go b/internal/state/util.go new file mode 100644 index 0000000..473ae51 --- /dev/null +++ b/internal/state/util.go @@ -0,0 +1,49 @@ +package state + +import ( + "errors" + "maps" +) + +var ( + ErrDuplicate = errors.New("store contains duplicates") +) + +// Join returns joined state entries of all active aids. +func Join(s Store) (Entries, error) { + var ( + aids []int + entries = make(Entries) + + el int + res Entries + loadErr error + ) + + if ln, err := s.List(); err != nil { + return nil, err + } else { + aids = ln + } + + for _, aid := range aids { + if _, err := s.Do(aid, func(c Cursor) { + res, loadErr = c.Load() + }); err != nil { + return nil, err + } + + if loadErr != nil { + return nil, loadErr + } + + // save expected length + el = len(entries) + len(res) + maps.Copy(entries, res) + if len(entries) != el { + return nil, ErrDuplicate + } + } + + return entries, nil +}