diff options
| author | Paul Buetow <paul@buetow.org> | 2023-06-12 23:15:28 +0300 |
|---|---|---|
| committer | Paul Buetow <paul@buetow.org> | 2023-06-12 23:15:28 +0300 |
| commit | fcd85ee5de82745211bdb4a1eef0077dc8a815d7 (patch) | |
| tree | 18cd661993e724f9b98557e722c6bbc5b9f35d1b /internal | |
| parent | cd91865979a5bbaaab79a703e36d1be729d95101 (diff) | |
can serialize and deserialise a vote from and to json
Diffstat (limited to 'internal')
| -rw-r--r-- | internal/vote/vote.go | 40 | ||||
| -rw-r--r-- | 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) + } +} |
