module Hpp.String (stringify, unquote, trimSpaces, breakOn, cons) where
import Data.Char (isSpace)
import Data.List (isPrefixOf)
stringify :: String -> String
stringify s = '"' : concatMap aux (strip s) ++ "\""
where aux '\\' = "\\\\"
aux '"' = "\\\""
aux c = [c]
strip = trimSpaces . dropWhile isSpace
unquote :: String -> String
unquote ('"':xs) = go xs
where go ['"'] = []
go [] = []
go (c:cs) = c : go cs
unquote xs = xs
trimSpaces :: String -> String
trimSpaces = trimEnd isSpace
trimEnd :: (a -> Bool) -> [a] -> [a]
trimEnd p = go id
where go _ [] = []
go acc (c:cs)
| p c = go (acc . (c:)) cs
| otherwise = acc (c : go id cs)
breakOn :: String -> String -> (String, String)
breakOn needle haystack = go 0 haystack
where go _ [] = (haystack, [])
go !i xs@(_:xs')
| needle `isPrefixOf` xs = (take i haystack, xs)
| otherwise = go (i+1) xs'
cons :: a -> [a] -> [a]
cons x xs = x : xs