Skip to content

Commit

Permalink
Add Data.Complex instances
Browse files Browse the repository at this point in the history
  • Loading branch information
TravisWhitaker committed Apr 6, 2024
1 parent c41604b commit edc2e19
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 0 deletions.
9 changes: 9 additions & 0 deletions src/Data/Aeson/Types/FromJSON.hs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ import Data.Aeson.Types.Internal
import Data.Aeson.Decoding.ByteString.Lazy
import Data.Aeson.Decoding.Conversion (unResult, toResultValue, lbsSpace)
import Data.Bits (unsafeShiftR)
import Data.Complex (Complex(..))
import Data.Fixed (Fixed, HasResolution (resolution), Nano)
import Data.Functor.Compose (Compose(..))
import Data.Functor.Identity (Identity(..))
Expand Down Expand Up @@ -1720,6 +1721,14 @@ instance (FromJSON a, Integral a) => FromJSON (Ratio a) where
then fail "Ratio denominator was 0"
else pure $ numerator % denominator

instance FromJSON a => FromJSON (Complex a) where
parseJSON = withArray "Complex" $ \c ->
let n = V.length c
in if n == 2
then (:+) <$> parseJSONElemAtIndex parseJSON 0 c
<*> parseJSONElemAtIndex parseJSON 1 c
else fail $ "cannot unpack array of length " ++ show n ++ "into a Complex"

-- | This instance includes a bounds check to prevent maliciously
-- large inputs to fill up the memory of the target system. You can
-- newtype 'Scientific' and provide your own instance using
Expand Down
11 changes: 11 additions & 0 deletions src/Data/Aeson/Types/ToJSON.hs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import Data.Aeson.Types.Internal
import qualified Data.Aeson.Key as Key
import qualified Data.Aeson.KeyMap as KM
import Data.Bits (unsafeShiftR)
import Data.Complex (Complex(..))
import Data.DList (DList)
import Data.Fixed (Fixed, HasResolution, Nano)
import Data.Foldable (toList)
Expand Down Expand Up @@ -1421,6 +1422,16 @@ instance (ToJSON a, Integral a) => ToJSON (Ratio a) where
"numerator" .= numerator r <>
"denominator" .= denominator r

instance ToJSON a => ToJSON (Complex a) where
toJSON (i :+ q) = Array $ V.create $ do
mv <- VM.unsafeNew 2
VM.unsafeWrite mv 0 (toJSON i)
VM.unsafeWrite mv 1 (toJSON q)
return mv
toEncoding (i :+ q) = E.list id
[ toEncoding i
, toEncoding q
]

instance HasResolution a => ToJSON (Fixed a) where
toJSON = Number . realToFrac
Expand Down

0 comments on commit edc2e19

Please sign in to comment.