From 50de1c5558202ffdd41dd300cd4bfcde29914faf Mon Sep 17 00:00:00 2001 From: Stefan Friese Date: Thu, 18 Apr 2024 00:18:39 +0200 Subject: [PATCH] reworking functions and errorhandling --- Main.hs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 52 insertions(+), 4 deletions(-) diff --git a/Main.hs b/Main.hs index f7b0900..262d25e 100644 --- a/Main.hs +++ b/Main.hs @@ -72,6 +72,34 @@ data Based = Decode { deriving(Show, Data, Typeable) -- helper functions + +convertToByteString :: String -> Either String BS.ByteString +convertToByteString str = + case BSU.fromString str of + Just bs -> Right bs + Nothing -> Left "Failed to convert string to ByteString." + +decodeFromBase91 :: C.ByteString -> Either String BS.ByteString + case B91.decode bs = + Just bs -> Right decoded + Nothing -> Left "Failed to decode from Base91." + + +encodeToBase64 :: C.ByteString -> Either String BS.ByteString +encodeToBase64 bs = + case B64.encode bs of + encoded | BS.null encoded -> Left "Failed to encode base64." + | otherwise -> Right encoded + +decodeFromBase64 :: C.ByteString -> Either String BS.ByteString +decodeFromBase64 bs = + case B64L.decodeLenient bs of + decoded | BS.null decoded -> Left "Failed to decode from base64." + | otherwise -> Right decoded + -- | otherwise -> Right (BSU.toString decoded) + -- Left err -> Left $ "Failed to decode from base64: " ++ err + -- Right decoded -> Right decoded + binToInt :: [Int] -> Int binToInt [] = 0 binToInt (x : xs) = x + 2 * binToInt xs @@ -82,13 +110,33 @@ octToInt (x : xs) = x + 8 * octToInt xs -- base functions -- without the show func, sequences like \n will not be shown as characters but will be executed as newline -dec91 = C.unpack . B91.decode + +-- dec91 = C.unpack . B91.decode +dec91 :: C.ByteString -> Either String String +dec91 input = do + decoded <- decodeFromBase91 input + -- return $ C.unpack decoded + -- is the same as + return (C.unpack decoded) + enc91 = B91.encode . BSU.fromString dec85 = C.unpack . U.fromRight . B85.decode . BSU.fromString enc85 = C.unpack . B85.encode . BSU.fromString --- dec64 = C.unpack . U.fromRight . B64.decode . BSU.fromString -dec64 = C.unpack . B64L.decodeLenient . BSU.fromString -enc64 = C.unpack . B64.encode . BSU.fromString + +-- dec64 = C.unpack . B64L.decodeLenient . BSU.fromString +dec64 :: String -> Either String String +dec64 input = do + byteString <- convertToByteString input + decoded <- decodeFromBase64 byteString + return $ BSU.toString decoded + +-- enc64 = C.unpack . B64.encode . BSU.fromString +enc64 :: String -> Either String String +enc64 input = do + byteString <- convertToByteString input + encoded <- encodeToBase64 byteString + return $ BS.unpack encoded + dec64url = C.unpack . U.fromRight . B64U.decode . BSU.fromString enc64url = C.unpack . B64U.encode . BSU.fromString decurl = HB.urlDecode