Created
January 5, 2025 00:58
-
-
Save Profpatsch/3d3c511fa169fa4a7503282f09872a05 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Builder where | |
import Data.ByteString.Builder qualified as Bytes | |
import Data.ByteString.Lazy qualified as Bytes.Lazy | |
import Data.Functor.Contravariant | |
import Data.String | |
import Data.Text.Lazy qualified as Text.Lazy | |
import Data.Text.Lazy.Builder qualified as Text | |
import Data.Text.Lazy.Builder.Int qualified as Text | |
import MyPrelude | |
newtype TextBuilder a = TextBuilder {unTextBuilder :: a -> Text.Builder} | |
deriving newtype (Semigroup, Monoid) | |
instance IsString (TextBuilder a) where | |
fromString s = TextBuilder $ \_ -> s & fromString | |
instance Contravariant TextBuilder where | |
contramap f (TextBuilder g) = TextBuilder $ g . f | |
-- | Convert a 'TextBuilder' to a strict 'Text' by applying it to a value. | |
buildText :: TextBuilder a -> a -> Text | |
buildText (TextBuilder f) a = f a & Text.toLazyText & toStrict | |
-- | Convert a 'TextBuilder' to a lazy 'Text' by applying it to a value. | |
buildTextLazy :: TextBuilder a -> a -> Text.Lazy.Text | |
buildTextLazy (TextBuilder f) a = f a & Text.toLazyText | |
newtype BytesBuilder a = BytesBuilder {unBytesBuilder :: a -> Bytes.Builder} | |
instance IsString (BytesBuilder a) where | |
fromString s = BytesBuilder $ \_ -> s & fromString | |
instance Contravariant BytesBuilder where | |
contramap f (BytesBuilder g) = BytesBuilder $ g . f | |
-- | Convert a 'BytesBuilder' to a strict 'ByteString' by applying it to a value. | |
buildBytes :: BytesBuilder a -> a -> ByteString | |
buildBytes (BytesBuilder b) a = b a & Bytes.toLazyByteString & toStrictBytes | |
-- | Convert a 'BytesBuilder' to a lazy 'ByteString' by applying it to a value. | |
buildBytesLazy :: BytesBuilder a -> a -> Bytes.Lazy.ByteString | |
buildBytesLazy (BytesBuilder b) a = b a & Bytes.toLazyByteString | |
textT :: TextBuilder Text | |
textT = TextBuilder Text.fromText | |
textLazyT :: TextBuilder Text.Lazy.Text | |
textLazyT = TextBuilder Text.fromLazyText | |
bytesB :: BytesBuilder ByteString | |
bytesB = BytesBuilder Bytes.byteString | |
bytesLazyB :: BytesBuilder Bytes.Lazy.ByteString | |
bytesLazyB = BytesBuilder Bytes.lazyByteString | |
utf8B :: BytesBuilder Text | |
utf8B = textToBytesUtf8 >$< bytesB | |
utf8LazyB :: BytesBuilder Text.Lazy.Text | |
utf8LazyB = textToBytesUtf8Lazy >$< bytesLazyB | |
intDecimalT :: TextBuilder Int | |
intDecimalT = TextBuilder Text.decimal | |
intDecimalNaturalT :: TextBuilder Natural | |
intDecimalNaturalT = TextBuilder Text.decimal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment