-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.hs
38 lines (31 loc) · 1.39 KB
/
Utils.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
module Utils where
import Data.Binary (Word8)
import Network.Socket
type Delimiter = Char
execAll :: [IO ()] -> IO ()
execAll [] = return ()
execAll (a:as) = do execAll as; a
getFieldDelimitedBy :: Delimiter -> String -> Int -> String
getFieldDelimitedBy delimiter input index = getFieldDelimitedBy' index input
where
getFieldDelimitedBy' :: Int -> String -> String
getFieldDelimitedBy' 0 a = takeWhile (/= delimiter) a
getFieldDelimitedBy' n a = getFieldDelimitedBy' (n - 1) (tail (dropWhile (/= delimiter) a))
getFieldsDelimitedBy :: Delimiter -> String -> [String]
getFieldsDelimitedBy delimiter = getFieldsDelimitedBy' []
where
getFieldsDelimitedBy' :: [String] -> String -> [String]
getFieldsDelimitedBy' buf "" = buf
getFieldsDelimitedBy' buf input = getFieldsDelimitedBy' ((takeWhile (/= delimiter) input) : buf) (clean (dropWhile (/= delimiter) input))
where
clean str@(c:cs)
| c == delimiter = cs
| otherwise = str
clean "" = ""
ip4StringToTuple :: String -> (Word8, Word8, Word8, Word8)
ip4StringToTuple addr = (parseAddrPart addr 0, parseAddrPart addr 1, parseAddrPart addr 2, parseAddrPart addr 3)
where
parseAddrPart :: String -> Int -> Word8
parseAddrPart a i = (read $ getFieldDelimitedBy '.' a i) :: Word8
ip4StringToHostAddress :: String -> HostAddress
ip4StringToHostAddress = tupleToHostAddress . ip4StringToTuple