bump 0.1.2.5
[htalkat.git] / Host.hs
blobc5ba26026da11fd29f89fd57fdd173cd83dae685
1 -- This file is part of htalkat
2 -- Copyright (C) 2021 Martin Bays <mbays@sdf.org>
3 --
4 -- This program is free software: you can redistribute it and/or modify
5 -- it under the terms of version 3 of the GNU General Public License as
6 -- published by the Free Software Foundation, or any later version.
7 --
8 -- You should have received a copy of the GNU General Public License
9 -- along with this program. If not, see http://www.gnu.org/licenses/.
11 {-# LANGUAGE Safe #-}
13 module Host where
15 import Control.Monad (msum)
16 import Data.List (elemIndices)
17 import Data.Maybe (fromMaybe)
18 import Safe (lastMay, readMay)
20 data Host = Host {hostName :: String, hostPort :: Int}
21 deriving (Eq,Ord,Show)
23 defaultTalkatPort :: Int
24 defaultTalkatPort = 5518
26 showHost :: Host -> String
27 showHost (Host name port) = name ++
28 (if port == defaultTalkatPort then "" else ":" ++ show port)
30 parseHost :: String -> Maybe Host
31 parseHost s = msum
32 [ (`Host` defaultTalkatPort) <$> decodeIPv6 s
33 , do
34 i <- lastMay $ elemIndices ':' s
35 let (h, ':':portStr) = splitAt i s
36 h' = fromMaybe h $ decodeIPv6 h
37 Host h' <$> readMay portStr
38 , pure $ Host s defaultTalkatPort
40 where
41 decodeIPv6 :: String -> Maybe String
42 decodeIPv6 ('[':rest) | Just ']' <- lastMay rest = Just $ init rest
43 decodeIPv6 _ = Nothing