diff options
author | Joris | 2016-03-26 20:29:15 +0100 |
---|---|---|
committer | Joris | 2016-03-26 20:29:36 +0100 |
commit | 2e411664ce8da96fd50340b1ecb9e6e2e16f6ca2 (patch) | |
tree | 4d9399723a470a2fcd24b1df05aeb481468492de /Data/ConfigManager/Parser | |
parent | 88aef982ff7a1be7fba2abf7264773b511608404 (diff) |
Parse durations
Diffstat (limited to 'Data/ConfigManager/Parser')
-rw-r--r-- | Data/ConfigManager/Parser/Duration.hs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/Data/ConfigManager/Parser/Duration.hs b/Data/ConfigManager/Parser/Duration.hs new file mode 100644 index 0000000..f169c55 --- /dev/null +++ b/Data/ConfigManager/Parser/Duration.hs @@ -0,0 +1,36 @@ +{-# LANGUAGE OverloadedStrings #-} + +module Data.ConfigManager.Parser.Duration + ( parseDuration + ) where + +import Control.Applicative ((<|>)) + +import Data.Text (Text) +import qualified Data.Text as T +import Data.Time.Clock (DiffTime) +import qualified Data.Time.Clock as Time + +import Text.Read (readMaybe) + +parseDuration :: Text -> Maybe DiffTime +parseDuration input = + case T.splitOn " " input of + [count, unit] -> do + n <- readMaybe . T.unpack $ count + let matchDuration singularUnit pluralUnit seconds = + if ((n == 0 || n == 1) && unit == singularUnit) || (n > 1 && unit == pluralUnit) + then Just . Time.secondsToDiffTime $ n * seconds + else Nothing + (matchDuration "second" "seconds" second) + <|> (matchDuration "minute" "minutes" minute) + <|> (matchDuration "hour" "hours" hour) + <|> (matchDuration "day" "days" day) + <|> (matchDuration "week" "weeks" week) + _ -> Nothing + where + second = 1 + minute = 60 * second + hour = 60 * minute + day = 24 * hour + week = 7 * day |