module Codec.Binary.QuotedPrintable
( EncIncData(..)
, EncIncRes(..)
, encodeInc
, encode
, DecIncData(..)
, DecIncRes(..)
, decodeInc
, decode
, chop
, unchop
) where
import Codec.Binary.Util
import Data.Char
import Data.Maybe
import Data.Word
encodeInc :: EncIncData -> EncIncRes String
encodeInc e = eI e
where
enc [] = []
enc (o:os)
| o < 33 || o == 61 || o > 126 = ('=' : toHex o) ++ enc os
| otherwise = chr (fromIntegral o) : enc os
eI EDone = EFinal []
eI (EChunk bs) = EPart (enc bs) encodeInc
encode :: [Word8] -> String
encode = encoder encodeInc
decodeInc :: DecIncData String -> DecIncRes String
decodeInc d = dI [] d
where
dI [] DDone = DFinal [] []
dI lo DDone = DFail [] lo
dI lo (DChunk s) = doDec [] (lo ++ s)
where
doDec acc [] = DPart acc (dI [])
doDec acc s'@('=':c0:c1:cs) = let
o = fromHex [c0, c1]
in if isJust o
then doDec (acc ++ [fromJust o]) cs
else DFail acc s'
doDec acc s'@(c:cs)
| c /= '=' = doDec (acc ++ [fromIntegral $ ord c]) cs
| otherwise = DPart acc (dI s')
decode :: String -> Maybe [Word8]
decode = decoder decodeInc
chop :: Int
-> String
-> [String]
chop n "" = []
chop n s = let
n' = max 3 $ n 1
_c i ts "" acc = ts : acc
_c i ts tss@('=' : tss') acc
| i + 2 < n' = _c (i + 1) ('=' : ts) tss' acc
| otherwise = _c 0 "" tss (('=' : ts) : acc)
_c i ts tss@(c : tss') acc
| i < n' = _c (i + 1) (c : ts) tss' acc
| otherwise = _c 0 "" tss (('=' : ts) : acc)
in map reverse . reverse $ _c 0 "" s []
unchop :: [String] -> String
unchop [] = ""
unchop (s : ss) = let
dropLast = last s == '='
len = length s
in if dropLast
then take (len 1) s ++ unchop ss
else s ++ unchop ss