Skip to content

Commit

Permalink
Merge pull request #6130 from chipaca/unsimplify-epoch-json
Browse files Browse the repository at this point in the history
snap: make Epoch's MarshalJSON not simplify
  • Loading branch information
chipaca authored Nov 13, 2018
2 parents eedf964 + 6b9a88c commit 2d204dc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 8 deletions.
7 changes: 6 additions & 1 deletion snap/epoch.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,12 @@ func (e *Epoch) simplify() interface{} {
}

func (e *Epoch) MarshalJSON() ([]byte, error) {
return json.Marshal(e.simplify())
// note the nil case doesn't happen unless called explicitly
if e == nil || (e.Read == nil && e.Write == nil) {
// lazy special case
return []byte(`{"read":[0],"write":[0]}`), nil
}
return json.Marshal(&structuredEpoch{Read: e.Read, Write: e.Write})
}

func (Epoch) MarshalYAML() (interface{}, error) {
Expand Down
21 changes: 14 additions & 7 deletions snap/epoch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -199,16 +199,23 @@ func (s *epochSuite) TestEpochMarshal(c *check.C) {
e *snap.Epoch
s string
}{
// {e: nil, s: `"0"`},
{e: &snap.Epoch{}, s: `"0"`},
{e: &snap.Epoch{Read: []uint32{0}, Write: []uint32{0}}, s: `"0"`},
{e: &snap.Epoch{Read: []uint32{0, 1}, Write: []uint32{1}}, s: `"1*"`},
{e: &snap.Epoch{Read: []uint32{1}, Write: []uint32{1}}, s: `"1"`},
{e: &snap.Epoch{Read: []uint32{399, 400}, Write: []uint32{400}}, s: `"400*"`},
{e: nil, s: `{"read":[0],"write":[0]}`},
{e: &snap.Epoch{}, s: `{"read":[0],"write":[0]}`},
{e: &snap.Epoch{Read: []uint32{0}, Write: []uint32{0}}, s: `{"read":[0],"write":[0]}`},
{e: &snap.Epoch{Read: []uint32{0, 1}, Write: []uint32{1}}, s: `{"read":[0,1],"write":[1]}`},
{e: &snap.Epoch{Read: []uint32{1}, Write: []uint32{1}}, s: `{"read":[1],"write":[1]}`},
{e: &snap.Epoch{Read: []uint32{399, 400}, Write: []uint32{400}}, s: `{"read":[399,400],"write":[400]}`},
{e: &snap.Epoch{Read: []uint32{1, 2, 3}, Write: []uint32{1, 2, 3}}, s: `{"read":[1,2,3],"write":[1,2,3]}`},
}
for _, test := range tests {
bs, err := json.Marshal(test.e)
bs, err := test.e.MarshalJSON()
c.Assert(err, check.IsNil)
c.Check(string(bs), check.Equals, test.s, check.Commentf(test.s))
if test.e == nil {
// json.Marshal((*foo)(nil)) is "null" no matter how hard you try
continue
}
bs, err = json.Marshal(test.e)
c.Assert(err, check.IsNil)
c.Check(string(bs), check.Equals, test.s, check.Commentf(test.s))
}
Expand Down

0 comments on commit 2d204dc

Please sign in to comment.