Data.Aeson.Encode.Pretty.ToEncoding: Use encodePrettyToTextBuilder as base

aeson-pretty implements by formatting using a text Builder, and the ByteString
is encoded from that. So instead of decoding the ByteString to produce Text or
Builder, use the Builder as the starting point, to match how aeson-pretty works
and save computation and weird backwards-decoding stuff.
This commit is contained in:
fr33domlover 2019-06-29 22:39:42 +00:00
parent 183e9a7754
commit 90cb4fcd88

View file

@ -24,21 +24,25 @@ where
import Data.Aeson (ToJSON, Value, encode, decode) import Data.Aeson (ToJSON, Value, encode, decode)
import Data.ByteString.Lazy (ByteString) import Data.ByteString.Lazy (ByteString)
import Data.Maybe (fromJust)
import Data.Text.Lazy (Text) import Data.Text.Lazy (Text)
import Data.Text.Lazy.Builder (Builder, fromLazyText) import Data.Text.Lazy.Builder (Builder, toLazyText)
import Data.Text.Lazy.Encoding (decodeUtf8) import Data.Text.Lazy.Encoding (encodeUtf8)
import qualified Data.Aeson.Encode.Pretty as P (encodePretty) import qualified Data.Aeson.Encode.Pretty as P
encodePretty :: ToJSON a => a -> ByteString encodePretty :: ToJSON a => a -> ByteString
encodePretty = P.encodePretty . fromJust . decodeValue . encode encodePretty = encodeUtf8 . encodePrettyToLazyText
where
decodeValue :: ByteString -> Maybe Value
decodeValue = decode
encodePrettyToLazyText :: ToJSON a => a -> Text encodePrettyToLazyText :: ToJSON a => a -> Text
encodePrettyToLazyText = decodeUtf8 . encodePretty encodePrettyToLazyText = toLazyText . encodePrettyToTextBuilder
encodePrettyToTextBuilder :: ToJSON a => a -> Builder encodePrettyToTextBuilder :: ToJSON a => a -> Builder
encodePrettyToTextBuilder = fromLazyText . encodePrettyToLazyText encodePrettyToTextBuilder =
P.encodePrettyToTextBuilder . decodeValue . encode
where
decodeValue :: ByteString -> Value
decodeValue b =
case decode b of
Nothing ->
error "encodePretty: Failed to decode encoded JSON into Value"
Just v -> v