implemented unescapeString
This commit is contained in:
@@ -24,13 +24,22 @@ License along with this program. If not, see
|
||||
|
||||
-}
|
||||
|
||||
{-# LANGUAGE LambdaCase #-}
|
||||
|
||||
module Network.GemServ (
|
||||
encodeRequest,
|
||||
escapeString
|
||||
escapeString,
|
||||
unescapeString
|
||||
) where
|
||||
|
||||
import Data.Char (ord)
|
||||
import Data.List (intercalate)
|
||||
import qualified Data.ByteString as BS
|
||||
import Data.ByteString.Builder (charUtf8, toLazyByteString)
|
||||
import qualified Data.ByteString.Lazy as BSL
|
||||
import Data.Char (ord, toLower)
|
||||
import Data.List (find, intercalate)
|
||||
import Data.Maybe (fromJust)
|
||||
import qualified Data.Text as T
|
||||
import Data.Text.Encoding (decodeUtf8')
|
||||
|
||||
import Network.GemServ.Types
|
||||
|
||||
@@ -61,6 +70,26 @@ escapeString = concatMap $ \ch ->
|
||||
low = n `mod` 16
|
||||
in [hexDigits !! high, hexDigits !! low]
|
||||
|
||||
-- | decode an escaped string back to its original value
|
||||
unescapeString :: String -> Maybe String
|
||||
unescapeString str = case decodeUtf8' $ BS.pack $ toBytes str of
|
||||
Right t -> Just $ T.unpack t
|
||||
_ -> Nothing
|
||||
where
|
||||
toBytes = \case
|
||||
"" -> []
|
||||
'%':h:l:sub -> let
|
||||
h' = toLower h
|
||||
l' = toLower l
|
||||
in if h' `elem` hexDigits && l' `elem` hexDigits
|
||||
then toByte h' l' : toBytes sub
|
||||
else fromIntegral (ord '%') : toBytes (h : l : sub)
|
||||
ch:sub ->
|
||||
BSL.unpack (toLazyByteString $ charUtf8 ch) ++ toBytes sub
|
||||
toByte h l = toNum h * 16 + toNum l
|
||||
toNum ch = fst $ fromJust $
|
||||
find (\x -> snd x == ch) $ zip [0..] hexDigits
|
||||
|
||||
hexDigits :: String
|
||||
hexDigits = ['0'..'9'] ++ ['a'..'f']
|
||||
|
||||
|
||||
Reference in New Issue
Block a user