module Data.Thyme.Clock.POSIX
( posixDayLength
, POSIXTime
, posixTime
, getPOSIXTime
) where
import Prelude
import Control.Lens
import Data.AdditiveGroup
import Data.Thyme.Internal.Micro
import Data.Thyme.Clock.Internal
import Foreign.C.Error (throwErrnoIfMinus1_)
import Foreign.C.Types
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable
type POSIXTime = NominalDiffTime
posixTime :: Iso' UTCTime POSIXTime
posixTime = iso (\ (UTCRep t) -> t ^-^ unixEpoch)
(UTCRep . (^+^) unixEpoch) where
unixEpoch = review microseconds $
40587 * 86400000000
getPOSIXTime :: IO POSIXTime
getPOSIXTime = allocaBytes (16) $ \ ptv -> do
throwErrnoIfMinus1_ "gettimeofday" $ gettimeofday ptv nullPtr
CTime sec <- (\hsc_ptr -> peekByteOff hsc_ptr 0) ptv
CSUSeconds usec <- (\hsc_ptr -> peekByteOff hsc_ptr 8) ptv
return . NominalDiffTime . Micro $
1000000 * fromIntegral sec + fromIntegral usec
foreign import ccall unsafe "time.h gettimeofday"
gettimeofday :: Ptr () -> Ptr () -> IO CInt