Skip to content

Commit

Permalink
Add FromDhall/ToDhall for LocalTime/ZonedTime/UTCTime (#2300)
Browse files Browse the repository at this point in the history
  • Loading branch information
amesgen authored Sep 11, 2021
1 parent fa11f0c commit a52a3e7
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
45 changes: 45 additions & 0 deletions dhall/src/Dhall/Marshal/Decode.hs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ module Dhall.Marshal.Decode
, timeOfDay
, day
, timeZone
, localTime
, zonedTime
, utcTime
-- ** Containers
, maybe
, pair
Expand Down Expand Up @@ -326,6 +329,15 @@ instance FromDhall Time.Day where
instance FromDhall Time.TimeZone where
autoWith _ = timeZone

instance FromDhall Time.LocalTime where
autoWith _ = localTime

instance FromDhall Time.ZonedTime where
autoWith _ = zonedTime

instance FromDhall Time.UTCTime where
autoWith _ = utcTime

{-| Note that this instance will throw errors in the presence of duplicates in
the list. To ignore duplicates, use `setIgnoringDuplicates`.
-}
Expand Down Expand Up @@ -950,6 +962,39 @@ timeZone = Decoder {..}

expected = pure TimeZone

{-| Decode `Time.LocalTime`
>>> input localTime "2020-01-01T12:34:56"
2020-01-01 12:34:56
-}
localTime :: Decoder Time.LocalTime
localTime = record $
Time.LocalTime
<$> field "date" day
<*> field "time" timeOfDay

{-| Decode `Time.ZonedTime`
>>> input zonedTime "2020-01-01T12:34:56+02:00"
2020-01-01 12:34:56 +0200
-}
zonedTime :: Decoder Time.ZonedTime
zonedTime = record $
adapt
<$> field "date" day
<*> field "time" timeOfDay
<*> field "timeZone" timeZone
where
adapt date time = Time.ZonedTime (Time.LocalTime date time)

{-| Decode `Time.UTCTime`
>>> input utcTime "2020-01-01T12:34:56+02:00"
2020-01-01 10:34:56 UTC
-}
utcTime :: Decoder Time.UTCTime
utcTime = Time.zonedTimeToUTC <$> zonedTime

{-| Decode a `Maybe`.
>>> input (maybe natural) "Some 1"
Expand Down
20 changes: 20 additions & 0 deletions dhall/src/Dhall/Marshal/Encode.hs
Original file line number Diff line number Diff line change
Expand Up @@ -333,6 +333,26 @@ instance ToDhall Time.TimeZone where

declared = TimeZone

instance ToDhall Time.LocalTime where
injectWith _ = recordEncoder $
adapt
>$< encodeField "date"
>*< encodeField "time"
where
adapt (Time.LocalTime date time) = (date, time)

instance ToDhall Time.ZonedTime where
injectWith _ = recordEncoder $
adapt
>$< encodeField "date"
>*< encodeField "time"
>*< encodeField "timeZone"
where
adapt (Time.ZonedTime (Time.LocalTime date time) timeZone) = (date, (time, timeZone))

instance ToDhall Time.UTCTime where
injectWith = contramap (Time.utcToZonedTime Time.utc) . injectWith

{-| Note that the output list will be sorted.
>>> let x = Data.Set.fromList ["mom", "hi" :: Text]
Expand Down

0 comments on commit a52a3e7

Please sign in to comment.