{-# LINE 1 "src/Data/Thyme/Clock/POSIX.hsc" #-}
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LINE 2 "src/Data/Thyme/Clock/POSIX.hsc" #-}


{-# LINE 4 "src/Data/Thyme/Clock/POSIX.hsc" #-}

{-# LINE 5 "src/Data/Thyme/Clock/POSIX.hsc" #-}

{-# LINE 6 "src/Data/Thyme/Clock/POSIX.hsc" #-}

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


{-# LINE 23 "src/Data/Thyme/Clock/POSIX.hsc" #-}
import Foreign.C.Error (throwErrnoIfMinus1_)
import Foreign.C.Types
import Foreign.Marshal.Alloc (allocaBytes)
import Foreign.Ptr (Ptr, nullPtr)
import Foreign.Storable

{-# LINE 29 "src/Data/Thyme/Clock/POSIX.hsc" #-}

type POSIXTime = NominalDiffTime

{-# INLINE posixTime #-}
posixTime :: Iso' UTCTime POSIXTime
posixTime = iso (\ (UTCRep t) -> t ^-^ unixEpoch)
        (UTCRep . (^+^) unixEpoch) where
    unixEpoch = review microseconds $
        {-ModifiedJulianDay-}40587 * {-posixDayLength-}86400000000

{-# INLINE getPOSIXTime #-}
getPOSIXTime :: IO POSIXTime

{-# LINE 54 "src/Data/Thyme/Clock/POSIX.hsc" #-}

getPOSIXTime = allocaBytes (16) $ \ ptv -> do
{-# LINE 56 "src/Data/Thyme/Clock/POSIX.hsc" #-}
    throwErrnoIfMinus1_ "gettimeofday" $ gettimeofday ptv nullPtr
    CTime sec <- (\hsc_ptr -> peekByteOff hsc_ptr 0) ptv
{-# LINE 58 "src/Data/Thyme/Clock/POSIX.hsc" #-}
    CSUSeconds usec <- (\hsc_ptr -> peekByteOff hsc_ptr 8) ptv
{-# LINE 59 "src/Data/Thyme/Clock/POSIX.hsc" #-}
    return . NominalDiffTime . Micro $
        1000000 * fromIntegral sec + fromIntegral usec

foreign import ccall unsafe "time.h gettimeofday"
    gettimeofday :: Ptr () -> Ptr () -> IO CInt


{-# LINE 66 "src/Data/Thyme/Clock/POSIX.hsc" #-}