From fcd85ee5de82745211bdb4a1eef0077dc8a815d7 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Mon, 12 Jun 2023 23:15:28 +0300 Subject: can serialize and deserialise a vote from and to json --- internal/vote/vote.go | 40 ++++++++++++++++++++++++++++++++++++++-- internal/vote/vote_test.go | 21 +++++++++++++++++++++ 2 files changed, 59 insertions(+), 2 deletions(-) diff --git a/internal/vote/vote.go b/internal/vote/vote.go index 7407848..f65b21d 100644 --- a/internal/vote/vote.go +++ b/internal/vote/vote.go @@ -1,6 +1,7 @@ package vote import ( + "encoding/json" "log" "strings" "time" @@ -13,7 +14,7 @@ const Expiry = 20 * time.Second type Vote struct { FromID string IDs []string - ExpiresAt time.Time + ExpiresAt time.Time `json:"-"` } func New(conf config.Config, message string) Vote { @@ -34,10 +35,45 @@ func New(conf config.Config, message string) Vote { ids = append(ids, id) } - return Vote{fromID, ids, time.Now().Add(Expiry)} + return Vote{ + FromID: fromID, + IDs: ids, + } +} + +func NewFromJSON(bytes []byte) (v Vote, err error) { + if err = json.Unmarshal(bytes, &v); err != nil { + return + } + v.ExpiresAt = time.Now().Add(Expiry) + return +} + +func (v Vote) ToJSON() ([]byte, error) { + return json.Marshal(v) } func (v Vote) Expired() bool { now := time.Now() return now.After(v.ExpiresAt) || now.Equal(v.ExpiresAt) } + +func (v Vote) equals(v2 Vote) bool { + if v.FromID != v2.FromID { + return false + } + + if len(v.IDs) != len(v2.IDs) { + return false + } + + for i, id := range v.IDs { + if id != v2.IDs[i] { + return false + } + } + + // Not comparing ExpiresAt + + return true +} diff --git a/internal/vote/vote_test.go b/internal/vote/vote_test.go index ca9e77c..8bc6647 100644 --- a/internal/vote/vote_test.go +++ b/internal/vote/vote_test.go @@ -48,3 +48,24 @@ func TestVoteExpiry(t *testing.T) { t.Errorf("Expected vote to be expired") } } + +func TestMarshalling(t *testing.T) { + var ( + conf = config.Config{Nodes: []string{"foo:1234", "bay:4321"}} + v = New(conf, "earth foo bar baz bay\n") + ) + + bytes, err := v.ToJSON() + if err != nil { + t.Errorf("unable to serialize vote to json: %v", err) + } + + v2, err := NewFromJSON(bytes) + if err != nil { + t.Errorf("unable to deserialize json to vote: %v", err) + } + + if !v.equals(v2) { + t.Errorf("serialized %v and deserialized %v votes differ", v, v2) + } +} -- cgit v1.2.3