{-# LANGUAGE OverloadedStrings #-}
module Data.MIME.Base64
(
b
, contentTransferEncodeBase64
, contentTransferEncodingBase64
) where
import Control.Lens (prism')
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as L
import qualified Data.ByteString.Base64 as B64
import qualified Data.ByteString.Base64.Lazy as L64
import Data.Word (Word8)
import Data.MIME.Types (ContentTransferEncoding)
isBase64Char :: Word8 -> Bool
isBase64Char c =
(c >= 0x41 && c <= 0x5a)
|| (c >= 0x61 && c <= 0x7a)
|| (c >= 0x30 && c <= 0x39)
|| c == 43
|| c == 47
|| c == 61
contentTransferEncodeBase64 :: B.ByteString -> B.ByteString
contentTransferEncodeBase64 = L.toStrict . wrap . L64.encode . L.fromStrict
where
wrap s = case L.splitAt 76 s of
("", _) -> ""
(l, s') -> l <> "\r\n" <> wrap s'
contentTransferDecodeBase64 :: B.ByteString -> Either String B.ByteString
contentTransferDecodeBase64 = B64.decode . B.filter isBase64Char
contentTransferEncodingBase64 :: ContentTransferEncoding
contentTransferEncodingBase64 = prism'
contentTransferEncodeBase64
(either (const Nothing) Just . contentTransferDecodeBase64)
b :: ContentTransferEncoding
b = prism'
B64.encode
(either (const Nothing) Just . contentTransferDecodeBase64)