Skip to content

Commit

Permalink
Update FromJSON TickNumber instance to match ToJSON instance (#1870)
Browse files Browse the repository at this point in the history
Fixes #1868.
  • Loading branch information
byorgey authored May 28, 2024
1 parent 902ceda commit 508c099
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/swarm-engine/Swarm/Game/Tick.hs
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,19 @@ import Data.Aeson qualified as A
import Data.Int (Int64)
import GHC.Generics (Generic)
import Prettyprinter (Pretty (..))
import Swarm.Util.JSON (optionsUnwrapUnary)
import Swarm.Util.WindowedCounter (Offsettable (..))

-- | A newtype representing a count of ticks (typically since the
-- start of a game).
newtype TickNumber = TickNumber {getTickNumber :: Int64}
deriving (Eq, Ord, Show, Read, Generic, FromJSON)
deriving (Eq, Ord, Show, Read, Generic)

instance ToJSON TickNumber where
toJSON = A.genericToJSON (A.defaultOptions {A.unwrapUnaryRecords = True})
toJSON = A.genericToJSON optionsUnwrapUnary

instance FromJSON TickNumber where
parseJSON = A.genericParseJSON optionsUnwrapUnary

-- | Add an offset to a 'TickNumber'.
addTicks :: Int -> TickNumber -> TickNumber
Expand Down
12 changes: 12 additions & 0 deletions src/swarm-util/Swarm/Util/JSON.hs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
-- |
-- SPDX-License-Identifier: BSD-3-Clause
--
-- Utilities for JSON de/serialization.
module Swarm.Util.JSON where

import Data.Aeson qualified as A

-- | @aeson@ options specifying to unwrap unary records so they are
-- encoded as a simple value instead of as a JSON object.
optionsUnwrapUnary :: A.Options
optionsUnwrapUnary = A.defaultOptions {A.unwrapUnaryRecords = True}
1 change: 1 addition & 0 deletions swarm.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -525,6 +525,7 @@ library swarm-util
Data.BoolExpr.Simplify
Swarm.Util
Swarm.Util.Erasable
Swarm.Util.JSON
Swarm.Util.Lens
Swarm.Util.OccurrenceEncoder
Swarm.Util.ReadableIORef
Expand Down

0 comments on commit 508c099

Please sign in to comment.