From 21f9bfaee3b6c85796eda8bbf30e46ae229e7865 Mon Sep 17 00:00:00 2001 From: Heindrich Paul Date: Thu, 30 May 2019 14:01:36 +0200 Subject: [PATCH] added marshalling to deckofCards Pile --- pile.go | 15 +++++++++++++++ pile_test.go | 22 ++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/pile.go b/pile.go index 20db8e0..e408885 100644 --- a/pile.go +++ b/pile.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + jsoniter "github.com/json-iterator/go" "github.com/twinj/uuid" ) @@ -175,3 +176,17 @@ func (z *Pile) GetCardAtID(index int) (*Draw, error) { draw.Success = true return draw, nil } + +//UnmarshalPile unmarshals a byte array into a pointer to a Pile for internal use. +func UnmarshalPile(data []byte) (*Pile, error) { + var r Pile + json := jsoniter.ConfigCompatibleWithStandardLibrary + err := json.Unmarshal(data, &r) + return &r, err +} + +//Marshal marshals a pointer to a Pile into a byte array for transmission. +func (z *Pile) Marshal() ([]byte, error) { + json := jsoniter.ConfigCompatibleWithStandardLibrary + return json.Marshal(z) +} diff --git a/pile_test.go b/pile_test.go index 31f441d..5e9f9f0 100644 --- a/pile_test.go +++ b/pile_test.go @@ -319,3 +319,25 @@ func TestPileString(t *testing.T) { t.FailNow() } } + +func TestPileUnmarshal(t *testing.T) { + pile := NewPile() + marshalPile, err := pile.Marshal() + if err != nil { + t.Logf("There was an error marshaling the pile: %s\n", err.Error()) + t.FailNow() + } + upile, err := UnmarshalPile(marshalPile) + if err != nil { + t.Logf("There was an error unmarshaling the pile: %s\n", err.Error()) + t.FailNow() + } + if pile.PileID != upile.PileID { + t.Logf("The PileID's do not match\n") + t.FailNow() + } + if pile.Remaining != upile.Remaining { + t.Logf("The Remaining cards do not match\n") + t.FailNow() + } +}