{-|
Module      : Foreign.Lua.Utf8
Copyright   : © 2018-2020 Albert Krewinkel
License     : MIT
Maintainer  : Albert Krewinkel <tarleb+hslua@zeitkraut.de>
Stability   : beta
Portability : portable

Encoding and decoding of String to and from UTF8.
-}
module Foreign.Lua.Utf8
  ( toString
  , toText
  , fromString
  , fromText
  ) where

import Data.ByteString (ByteString)
import Data.Text (Text)

import qualified Data.Text as T
import qualified Data.Text.Encoding as TextEncoding
import qualified Data.Text.Encoding.Error as TextEncoding

-- | Decode @'ByteString'@ to @'String'@ using UTF-8. Invalid input
-- bytes are replaced with the Unicode replacement character U+FFFD.
toString :: ByteString -> String
toString :: ByteString -> String
toString = Text -> String
T.unpack (Text -> String) -> (ByteString -> Text) -> ByteString -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Text
toText
{-# INLINABLE toString #-}

-- | Decode @'ByteString'@ to @'Text'@ using UTF-8. Invalid input
-- bytes are replaced with the Unicode replacement character U+FFFD.
toText :: ByteString -> Text
toText :: ByteString -> Text
toText = OnDecodeError -> ByteString -> Text
TextEncoding.decodeUtf8With OnDecodeError
TextEncoding.lenientDecode
{-# INLINABLE toText #-}

-- | Encode @'String'@ to @'ByteString'@ using UTF-8.
fromString :: String -> ByteString
fromString :: String -> ByteString
fromString = Text -> ByteString
TextEncoding.encodeUtf8 (Text -> ByteString) -> (String -> Text) -> String -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. String -> Text
T.pack
{-# INLINABLE fromString #-}

-- | Encode @'Text'@ to @'ByteString'@ using UTF-8.
fromText :: Text -> ByteString
fromText :: Text -> ByteString
fromText = Text -> ByteString
TextEncoding.encodeUtf8
{-# INLINABLE fromText #-}