module Codec.Binary.Xx
( EncIncData(..)
, EncIncRes(..)
, encodeInc
, encode
, DecIncData(..)
, DecIncRes(..)
, decodeInc
, decode
, chop
, unchop
) where
import Codec.Binary.Util
import Control.Monad
import Data.Array
import Data.Bits
import Data.Maybe
import Data.Word
import qualified Data.Map as M
_encMap = zip [0..] "+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
encodeArray :: Array Word8 Char
encodeArray = array (0, 64) _encMap
decodeMap :: M.Map Char Word8
decodeMap = M.fromList [(snd i, fst i) | i <- _encMap]
encodeInc :: EncIncData -> EncIncRes String
encodeInc e = eI [] e
where
enc3 [o1, o2, o3] = map (encodeArray !) [i1, i2, i3, i4]
where
i1 = o1 `shiftR` 2
i2 = (o1 `shiftL` 4 .|. o2 `shiftR` 4) .&. 0x3f
i3 = (o2 `shiftL` 2 .|. o3 `shiftR` 6) .&. 0x3f
i4 = o3 .&. 0x3f
eI [] EDone = EFinal []
eI [o1] EDone = EFinal $ take 2 $ enc3 [o1, 0, 0]
eI [o1, o2] EDone = EFinal $ take 3 $ enc3 [o1, o2, 0]
eI lo (EChunk bs) = doEnc [] (lo ++ bs)
where
doEnc acc (o1:o2:o3:os) = doEnc (acc ++ enc3 [o1, o2, o3]) os
doEnc acc os = EPart acc (eI os)
encode :: [Word8] -> String
encode = encoder encodeInc
decodeInc :: DecIncData String -> DecIncRes String
decodeInc d = dI [] d
where
dec4 cs = let
ds = map (flip M.lookup decodeMap) cs
[e1, e2, e3, e4] = map fromJust ds
o1 = e1 `shiftL` 2 .|. e2 `shiftR` 4
o2 = e2 `shiftL` 4 .|. e3 `shiftR` 2
o3 = e3 `shiftL` 6 .|. e4
allJust = and . map isJust
in if allJust ds
then Just [o1, o2, o3]
else Nothing
dI [] DDone = DFinal [] []
dI lo@[c1, c2] DDone = maybe
(DFail [] lo)
(\ bs -> DFinal (take 1 bs) [])
(dec4 [c1, c2, '+', '+'])
dI lo@[c1, c2, c3] DDone = maybe
(DFail [] lo)
(\ bs -> DFinal (take 2 bs) [])
(dec4 [c1, c2, c3, '+'])
dI lo DDone = DFail [] lo
dI lo (DChunk s) = doDec [] (lo ++ s)
where
doDec acc s'@(c1:c2:c3:c4:cs) = maybe
(DFail acc s')
(\ bs -> doDec (acc ++ bs) cs)
(dec4 [c1, c2, c3, c4])
doDec acc s' = DPart acc (dI s')
decode :: String
-> Maybe [Word8]
decode = decoder decodeInc
chop :: Int
-> String
-> [String]
chop n "" = []
chop n s = let
enc_len | n < 5 = 4
| n >= 85 = 84
| otherwise = min 64 $ (n 1) `div` 4 * 4
enc_line = take enc_len s
act_len = fromIntegral $ case (length enc_line `divMod` 4) of
(l, 0) -> l * 3
(l, 2) -> l * 3 + 1
(l, 3) -> l * 3 + 2
len = (encodeArray ! act_len)
in (len : enc_line) : chop n (drop enc_len s)
unchop :: [String]
-> String
unchop ss = let
singleUnchop (l : cs) = let
act_len = fromIntegral $ decodeMap M.! l
enc_len = case (act_len `divMod` 3) of
(n, 0) -> n * 4
(n, 1) -> n * 4 + 2
(n, 2) -> n * 4 + 3
in take enc_len cs
in foldr ((++) . singleUnchop) "" ss