Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add FromLazyAvro instances for logical types #136

Merged
merged 1 commit into from
Feb 18, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/Data/Avro/Decode/Lazy/FromLazyAvro.hs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import Data.Avro.Decode.Lazy.LazyValue as T
import qualified Data.Avro.Encode as E
import Data.Avro.HasAvroSchema
import Data.Avro.Schema as S
import Data.Avro.Types.Decimal as D
import Data.Avro.Types.Time
import qualified Data.ByteString as B
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BL
Expand All @@ -25,9 +27,12 @@ import Data.Tagged
import Data.Text (Text)
import qualified Data.Text as Text
import qualified Data.Text.Lazy as TL
import qualified Data.Time as Time
import qualified Data.UUID as UUID
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as U
import Data.Word
import GHC.TypeLits

-- | 'FromLazyAvro' is a clone of 'FromAvro' except that
-- it works for lazy values ('LazyValue').
Expand Down Expand Up @@ -97,6 +102,28 @@ instance FromLazyAvro Float where
fromLazyAvro (T.Float f) = pure f
fromLazyAvro v = badValue v "Float"

instance (KnownNat p, KnownNat s) => FromLazyAvro (D.Decimal p s) where
fromLazyAvro (T.Long n) = pure $ D.fromUnderlyingValue $ fromIntegral n
fromLazyAvro (T.Int n) = pure $ D.fromUnderlyingValue $ fromIntegral n
fromLazyAvro v = badValue v "Decimal"

instance FromLazyAvro UUID.UUID where
fromLazyAvro v@(T.String s)
= case UUID.fromText s of
Nothing -> badValue v "UUID"
Just u -> pure u
fromLazyAvro v = badValue v "UUID"

instance FromLazyAvro Time.Day where
fromLazyAvro (T.Int v) = pure $ fromDaysSinceEpoch (toInteger v)
fromLazyAvro (T.Long v) = pure $ fromDaysSinceEpoch (toInteger v)
fromLazyAvro v = badValue v "Date"

instance FromLazyAvro Time.DiffTime where
fromLazyAvro (T.Int v) = pure $ microsToDiffTime (toInteger v)
fromLazyAvro (T.Long v) = pure $ microsToDiffTime (toInteger v)
fromLazyAvro v = badValue v "TimeMicros"

instance FromLazyAvro a => FromLazyAvro (Maybe a) where
fromLazyAvro (T.Union ts _ v) = case (V.toList ts, v) of
([S.Null, _], T.Null) -> pure Nothing
Expand Down