Debian Codegraph @

Data/Hourglass/Internal/Win.hs

raw
1 -- |
2 -- Module : Data.Hourglass.Internal.Win
3 -- License : BSD-style
4 -- Maintainer : Vincent Hanquez <[email protected]>
5 -- Stability : experimental
6 -- Portability : unknown
7 --
8 -- Time lowlevel helpers binding to Windows
9 --
10 {-# LANGUAGE ForeignFunctionInterface #-}
11 {-# LANGUAGE CPP #-}
12 module Data.Hourglass.Internal.Win
13 ( dateTimeFromUnixEpochP
14 , dateTimeFromUnixEpoch
15 , systemGetTimezone
16 , systemGetElapsed
17 , systemGetElapsedP
18 ) where
19
20 import System.IO.Unsafe
21 import System.Win32.Time
22 import Data.Hourglass.Types
23 import Data.Int (Int64)
24
25 unixDiff :: Int64
26 unixDiff = 11644473600
27
28 toFileTime :: Elapsed -> FILETIME
29 toFileTime (Elapsed (Seconds s)) = FILETIME val
30 where val = fromIntegral (s + unixDiff) * 10000000
31
32 toElapsedP :: FILETIME -> ElapsedP
33 toElapsedP (FILETIME w) = ElapsedP (Elapsed $ Seconds s) (NanoSeconds ns)
34 where (sWin, hundredNs) = w `divMod` 10000000
35 ns = fromIntegral (hundredNs * 100)
36 s = fromIntegral sWin - unixDiff
37
38 toElapsed :: FILETIME -> Elapsed
39 toElapsed (FILETIME w) = Elapsed (Seconds s)
40 where s = fromIntegral (fst (w `divMod` 10000000)) - unixDiff
41
42 callSystemTime :: Elapsed -> SYSTEMTIME
43 callSystemTime e = unsafePerformIO (fileTimeToSystemTime (toFileTime e))
44 {-# NOINLINE callSystemTime #-}
45
46 dateTimeFromUnixEpochP :: ElapsedP -> DateTime
47 dateTimeFromUnixEpochP (ElapsedP e ns) = toDateTime $ callSystemTime e
48 where toDateTime (SYSTEMTIME wY wM _ wD wH wMin wS _) =
49 DateTime (Date (fi wY) (toEnum $ fi $ wM - 1) (fi wD))
50 (TimeOfDay (fi wH) (fi wMin) (fi wS) ns)
51 fi :: (Integral a, Num b) => a -> b
52 fi = fromIntegral
53
54 dateTimeFromUnixEpoch :: Elapsed -> DateTime
55 dateTimeFromUnixEpoch e = toDateTime $ callSystemTime e
56 where toDateTime (SYSTEMTIME wY wM _ wD wH wMin wS _) =
57 DateTime (Date (fi wY) (toEnum $ fi $ wM - 1) (fi wD))
58 (TimeOfDay (fi wH) (fi wMin) (fi wS) 0)
59 fi :: (Integral a, Num b) => a -> b
60 fi = fromIntegral
61
62 systemGetTimezone :: IO TimezoneOffset
63 systemGetTimezone = do
64 (tzMode,tzInfo) <- getTimeZoneInformation
65 case tzMode of
66 TzIdDaylight -> return $ toTO (tziBias tzInfo + tziDaylightBias tzInfo)
67 TzIdStandard -> return $ toTO (tziBias tzInfo + tziStandardBias tzInfo)
68 TzIdUnknown -> return $ toTO (tziBias tzInfo)
69 where
70 -- a negative value represent value how to go from local to UTC,
71 -- whereas TimezoneOffset represent the offset to go from UTC to local.
72 -- here we negate the bias to get the proper value represented.
73 toTO = TimezoneOffset . fromIntegral . negate
74
75 systemGetElapsedP :: IO ElapsedP
76 systemGetElapsedP = toElapsedP `fmap` getSystemTimeAsFileTime
77
78 systemGetElapsed :: IO Elapsed
79 systemGetElapsed = toElapsed `fmap` getSystemTimeAsFileTime