{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ViewPatterns #-}
module System.IO.Utf8.Internal
( EncodingAction (..)
, chooseBestEncPure
, chooseBestEnc
) where
import Data.List (isSuffixOf)
import GHC.IO.Encoding (TextEncoding, textEncodingName, utf8)
import qualified System.IO as IO
data EncodingAction
= Keep
| ChangeFromTo TextEncoding String
chooseBestEncPure
:: Bool
-> Maybe String
-> Maybe String
chooseBestEncPure :: Bool -> Maybe String -> Maybe String
chooseBestEncPure Bool
_ Maybe String
Nothing = Maybe String
forall a. Maybe a
Nothing
chooseBestEncPure Bool
_ (Just String
"UTF-8") = Maybe String
forall a. Maybe a
Nothing
chooseBestEncPure Bool
False Maybe String
_ = String -> Maybe String
forall a. a -> Maybe a
Just String
"UTF-8"
chooseBestEncPure Bool
True (Just String
name)
| String
"//TRANSLIT" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` String
name = Maybe String
forall a. Maybe a
Nothing
| Bool
otherwise = String -> Maybe String
forall a. a -> Maybe a
Just (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$ String
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"//TRANSLIT"
chooseBestEnc
:: IO.Handle
-> (IO.Handle -> IO Bool)
-> Maybe TextEncoding
-> IO EncodingAction
chooseBestEnc :: Handle
-> (Handle -> IO Bool) -> Maybe TextEncoding -> IO EncodingAction
chooseBestEnc Handle
_ Handle -> IO Bool
_ Maybe TextEncoding
Nothing = EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure EncodingAction
Keep
chooseBestEnc Handle
h Handle -> IO Bool
hIsTerm (Just TextEncoding
enc) = case TextEncoding -> String
textEncodingName TextEncoding
enc of
String
"UTF-8" -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure EncodingAction
Keep
String
name
| String
"//TRANSLIT" String -> String -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` String
name -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure EncodingAction
Keep
| Bool
otherwise -> Handle -> IO Bool
hIsTerm Handle
h IO Bool -> (Bool -> IO EncodingAction) -> IO EncodingAction
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
Bool
False -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodingAction -> IO EncodingAction)
-> EncodingAction -> IO EncodingAction
forall a b. (a -> b) -> a -> b
$ TextEncoding -> String -> EncodingAction
ChangeFromTo TextEncoding
enc (TextEncoding -> String
textEncodingName TextEncoding
utf8)
Bool
True -> EncodingAction -> IO EncodingAction
forall (f :: * -> *) a. Applicative f => a -> f a
pure (EncodingAction -> IO EncodingAction)
-> EncodingAction -> IO EncodingAction
forall a b. (a -> b) -> a -> b
$ TextEncoding -> String -> EncodingAction
ChangeFromTo TextEncoding
enc (String
name String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"//TRANSLIT")