Skip to content

Commit

Permalink
Merge PR #63
Browse files Browse the repository at this point in the history
  • Loading branch information
kazu-yamamoto committed May 28, 2024
2 parents a0e38a4 + 75c5585 commit d7ec7d3
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 6 deletions.
3 changes: 2 additions & 1 deletion Data/UnixTime/Sys.hsc
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
{-# LANGUAGE CApiFFI #-}
{-# LANGUAGE ForeignFunctionInterface #-}

module Data.UnixTime.Sys (getUnixTime) where
Expand All @@ -17,7 +18,7 @@ import Foreign.Storable
type CTimeVal = ()
type CTimeZone = ()

foreign import ccall unsafe "gettimeofday"
foreign import capi unsafe "sys/time.h gettimeofday"
c_gettimeofday :: Ptr CTimeVal -> Ptr CTimeZone -> IO CInt

-- |
Expand Down
25 changes: 21 additions & 4 deletions Data/UnixTime/Types.hsc
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,29 @@ instance Storable UnixTime where
(#poke struct timeval, tv_sec) ptr (fromIntegral sec :: Word32)
(#poke struct timeval, tv_usec) ptr (utMicroSeconds ut)
#else
peek ptr = UnixTime
<$> (#peek struct timeval, tv_sec) ptr
<*> (#peek struct timeval, tv_usec) ptr
-- On Unix, the struct `timeval` is defined as
--
-- struct timeval
-- {
-- time_t tv_sec;
-- suseconds_t tv_usec;
-- };
--
-- The type `suseconds_t` is a signed integer type capable of storing
-- values at least in the range `[-1, 1000000]`. It's size is platform
-- specific, and it is 8 bytes long on 64-bit platforms.
--
-- Here we peek `tv_usec` using the `CSUSeconds` type and then convert it
-- to `Int32` (the type of `utMicroSeconds`) relying on the fact that
-- `tv_usec` is no bigger than `1000000`, and hence we will not overflow.
peek ptr = do
sec <- (#peek struct timeval, tv_sec) ptr
CSUSeconds msec <- (#peek struct timeval, tv_usec) ptr
return $ UnixTime sec (fromIntegral msec)
poke ptr ut = do
let msec = CSUSeconds $ fromIntegral (utMicroSeconds ut)
(#poke struct timeval, tv_sec) ptr (utSeconds ut)
(#poke struct timeval, tv_usec) ptr (utMicroSeconds ut)
(#poke struct timeval, tv_usec) ptr msec
#endif

#if __GLASGOW_HASKELL__ >= 704
Expand Down
2 changes: 1 addition & 1 deletion unix-time.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ library
include-dirs: cbits
ghc-options: -Wall
build-depends:
base >=4 && <5,
base >=4.4 && <5,
bytestring,
old-time,
binary
Expand Down

0 comments on commit d7ec7d3

Please sign in to comment.