{-# LANGUAGE CPP, DeriveDataTypeable #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
module Data.Text.Encoding.Error
(
UnicodeException(..)
, OnError
, OnDecodeError
, OnEncodeError
, lenientDecode
, strictDecode
, strictEncode
, ignore
, replace
) where
import Control.DeepSeq (NFData (..))
import Control.Exception (Exception, throw)
import Data.Typeable (Typeable)
import Data.Word (Word8)
import Numeric (showHex)
type OnError a b = String -> Maybe a -> Maybe b
type OnDecodeError = OnError Word8 Char
type OnEncodeError = OnError Char Word8
data UnicodeException =
DecodeError String (Maybe Word8)
| EncodeError String (Maybe Char)
deriving (Eq, Typeable)
showUnicodeException :: UnicodeException -> String
showUnicodeException (DecodeError desc (Just w))
= "Cannot decode byte '\\x" ++ showHex w ("': " ++ desc)
showUnicodeException (DecodeError desc Nothing)
= "Cannot decode input: " ++ desc
showUnicodeException (EncodeError desc (Just c))
= "Cannot encode character '\\x" ++ showHex (fromEnum c) ("': " ++ desc)
showUnicodeException (EncodeError desc Nothing)
= "Cannot encode input: " ++ desc
instance Show UnicodeException where
show = showUnicodeException
instance Exception UnicodeException
instance NFData UnicodeException where
rnf (DecodeError desc w) = rnf desc `seq` rnf w `seq` ()
rnf (EncodeError desc c) = rnf desc `seq` rnf c `seq` ()
strictDecode :: OnDecodeError
strictDecode desc c = throw (DecodeError desc c)
lenientDecode :: OnDecodeError
lenientDecode _ _ = Just '\xfffd'
strictEncode :: OnEncodeError
strictEncode desc c = throw (EncodeError desc c)
ignore :: OnError a b
ignore _ _ = Nothing
replace :: b -> OnError a b
replace c _ _ = Just c