Created
May 20, 2022 23:36
-
-
Save decapo01/54dbba265bacd11b5e826bee12deb51b to your computer and use it in GitHub Desktop.
String conversion typeclasses for the major string types in haskell
This file contains 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
{-# LANGUAGE FlexibleInstances #-} | |
module Common.StringUtils where | |
import qualified Data.Text as T | |
import qualified Data.Text.Encoding as En | |
import qualified Data.Text.Lazy as Lt | |
import qualified Data.Text.Lazy.Encoding as Len | |
import qualified Data.ByteString as Bs | |
import qualified Data.ByteString.Lazy as Lbs | |
type Text = T.Text | |
type LazyText = Lt.Text | |
type ByteString = Bs.ByteString | |
type LazyByteString = Lbs.ByteString | |
class ToString a where | |
toString :: a -> String | |
instance ToString T.Text where | |
toString = T.unpack | |
instance ToString LazyText where | |
toString = Lt.unpack | |
instance ToString Bs.ByteString where | |
toString = T.unpack . En.decodeUtf8 | |
instance ToString LazyByteString where | |
toString = Lt.unpack . Len.decodeUtf8 | |
class ToText a where | |
toText :: a -> T.Text | |
instance ToText String where | |
toText = T.pack | |
instance ToText LazyText where | |
toText = Lt.toStrict | |
instance ToText Bs.ByteString where | |
toText = En.decodeUtf8 | |
instance ToText LazyByteString where | |
toText = Lt.toStrict . Len.decodeUtf8 | |
class ToLazyText a where | |
toLazyText :: a -> LazyText | |
instance ToLazyText String where | |
toLazyText = Lt.pack | |
instance ToLazyText T.Text where | |
toLazyText = Lt.fromStrict | |
instance ToLazyText Bs.ByteString where | |
toLazyText = Lt.fromStrict . En.decodeUtf8 | |
instance ToLazyText LazyByteString where | |
toLazyText = Len.decodeUtf8 | |
class ToByteString a where | |
toByteString :: a -> Bs.ByteString | |
instance ToByteString String where | |
toByteString = En.encodeUtf8 . T.pack | |
instance ToByteString T.Text where | |
toByteString = En.encodeUtf8 | |
instance ToByteString LazyText where | |
toByteString = Lbs.toStrict . Len.encodeUtf8 | |
instance ToByteString LazyByteString where | |
toByteString = Lbs.toStrict | |
class ToLazyByteString a where | |
toLazyByteString :: a -> LazyByteString | |
instance ToLazyByteString String where | |
toLazyByteString = Len.encodeUtf8 . Lt.pack | |
instance ToLazyByteString Text where | |
toLazyByteString = Lbs.fromStrict . En.encodeUtf8 | |
instance ToLazyByteString LazyText where | |
toLazyByteString = Len.encodeUtf8 | |
instance ToLazyByteString ByteString where | |
toLazyByteString = Lbs.fromStrict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment