1 {-# LANGUAGE DeriveDataTypeable         #-}
    2 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
    3 
    4 module Snap.Internal.Http.Server.Clock
    5   ( ClockTime
    6   , getClockTime
    7   , sleepFor
    8   , sleepSecs
    9   , fromSecs
   10   , toSecs
   11   ) where
   12 
   13 import           Control.Concurrent (threadDelay)
   14 import qualified System.Clock       as Clock
   15 
   16 type ClockTime = Clock.TimeSpec
   17 
   18 ------------------------------------------------------------------------------
   19 sleepFor :: ClockTime -> IO ()
   20 sleepFor t = threadDelay $ fromIntegral d
   21   where
   22     d  = (Clock.nsec t `div` 1000) + (1000000 * Clock.sec t)
   23 
   24 
   25 ------------------------------------------------------------------------------
   26 sleepSecs :: Double -> IO ()
   27 sleepSecs = sleepFor . fromSecs
   28 
   29 
   30 ------------------------------------------------------------------------------
   31 getClockTime :: IO ClockTime
   32 getClockTime = Clock.getTime Clock.Monotonic
   33 
   34 
   35 ------------------------------------------------------------------------------
   36 fromSecs :: Double -> ClockTime
   37 fromSecs d = let (s, r) = properFraction d
   38              in Clock.TimeSpec s (truncate $! 1000000000 * r)
   39 
   40 
   41 ------------------------------------------------------------------------------
   42 toSecs :: ClockTime -> Double
   43 toSecs t = fromIntegral (Clock.sec t) +
   44            fromIntegral (Clock.nsec t) / 1000000000.0