module Network.Email.Charset
(
Charset
, charsetName
, charsets
, lookupCharset
, defaultCharset
, fromUnicode
, toUnicode
) where
import Prelude hiding (lookup)
import Data.ByteString (ByteString)
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Text (Text)
import qualified Data.Text.ICU.Convert as ICU
import System.IO.Unsafe
newtype Charset = Charset String
deriving (Show)
instance Eq Charset where
a == b = compare a b == EQ
instance Ord Charset where
compare (Charset a) (Charset b) = ICU.compareNames a b
charsetName :: Charset -> String
charsetName (Charset s) = s
charsets :: Set Charset
charsets = Set.fromList . map Charset . filter legalName $
concatMap ICU.aliases ICU.converterNames
where
legalName = all (`notElem` ",.=?")
lookupCharset :: String -> Maybe Charset
lookupCharset name = case Set.lookupLE c charsets of
Just c' | c' == c -> Just c'
_ -> Nothing
where
c = Charset name
defaultCharset :: Charset
defaultCharset = Charset "UTF-8"
unsafeLoad :: Charset -> ICU.Converter
unsafeLoad c = unsafePerformIO $ ICU.open (charsetName c) (Just True)
fromUnicode :: Charset -> Text -> ByteString
fromUnicode = ICU.fromUnicode . unsafeLoad
toUnicode :: Charset -> ByteString -> Text
toUnicode = ICU.toUnicode . unsafeLoad