Skip to content

UTF-8 Conversion Functions #2

@RobertFischer

Description

@RobertFischer

It'd be nice to have explicit functions for converting ByteString to and from UTF8, since that's the common use case.

This is the code that I find very useful in my local library:

asUTF8 :: (ToText a, FromText (UTF8 b)) => a -> b
asUTF8 = unUTF8 . fromText . toText
{-# INLINE asUTF8 #-}
{-# SPECIALIZE INLINE asUTF8 :: String-> LazyByteString          #-}
{-# SPECIALIZE INLINE asUTF8 :: StrictText -> LazyByteString     #-}
{-# SPECIALIZE INLINE asUTF8 :: LazyText -> LazyByteString       #-}
{-# SPECIALIZE INLINE asUTF8 :: String-> StrictByteString        #-}
{-# SPECIALIZE INLINE asUTF8 :: StrictText -> StrictByteString   #-}
{-# SPECIALIZE INLINE asUTF8 :: LazyText -> StrictByteString     #-}
{-# SPECIALIZE INLINE asUTF8 :: String-> ShortByteString         #-}
{-# SPECIALIZE INLINE asUTF8 :: StrictText -> ShortByteString    #-}
{-# SPECIALIZE INLINE asUTF8 :: LazyText -> ShortByteString      #-}

toUTF8 :: (DecodeText f (UTF8 a), FromText b) => a -> f b
toUTF8 = decodeConvertText . UTF8
{-# INLINE toUTF8 #-}
{-# SPECIALIZE INLINE toUTF8 :: LazyByteString -> Maybe String       #-}
{-# SPECIALIZE INLINE toUTF8 :: LazyByteString -> Maybe StrictText   #-}
{-# SPECIALIZE INLINE toUTF8 :: LazyByteString -> Maybe LazyText     #-}
{-# SPECIALIZE INLINE toUTF8 :: StrictByteString -> Maybe String     #-}
{-# SPECIALIZE INLINE toUTF8 :: StrictByteString -> Maybe StrictText #-}
{-# SPECIALIZE INLINE toUTF8 :: StrictByteString -> Maybe LazyText   #-}
{-# SPECIALIZE INLINE toUTF8 :: ShortByteString -> Maybe String      #-}
{-# SPECIALIZE INLINE toUTF8 :: ShortByteString -> Maybe StrictText  #-}
{-# SPECIALIZE INLINE toUTF8 :: ShortByteString -> Maybe LazyText    #-}

If this is something you're interested in, let me know, and I'm happy to submit a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions