Skip to content

Commit

Permalink
Merge pull request #68 from Mathnerd314/seconds
Browse files Browse the repository at this point in the history
"Seconds" RealFrac instance
  • Loading branch information
CetinSert authored Jul 13, 2021
2 parents bc5a1b6 + 27a1111 commit 85ecc2f
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
32 changes: 32 additions & 0 deletions System/Clock.hsc
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ module System.Clock
) where

import Control.Applicative ((<$>), (<*>))
import Data.Coerce
import Data.Int
import Data.Word
import Data.Ratio
Expand Down Expand Up @@ -283,3 +284,34 @@ diffTimeSpec ts1 ts2 = abs (ts1 - ts2)
-- | TimeSpec as nano seconds.
timeSpecAsNanoSecs :: TimeSpec -> Integer
timeSpecAsNanoSecs (TimeSpec s n) = toInteger s * s2ns + toInteger n

newtype Seconds = Seconds TimeSpec
deriving (Generic, Read, Show, Typeable, Eq, Ord, Storable)

instance Num Seconds where
fromInteger n = Seconds $ TimeSpec (fromInteger n) 0
Seconds a * Seconds b = Seconds $ a * b `div` s2ns
(+) = coerce ((+) :: TimeSpec -> TimeSpec -> TimeSpec)
(-) = coerce ((-) :: TimeSpec -> TimeSpec -> TimeSpec)
negate = coerce (negate :: TimeSpec -> TimeSpec)
abs = coerce (abs :: TimeSpec -> TimeSpec)
signum = coerce (signum :: TimeSpec -> TimeSpec)

instance Enum Seconds where
succ x = x + 1
pred x = x - 1
toEnum x = Seconds . normalize $ TimeSpec (fromIntegral x) 0
fromEnum (Seconds (TimeSpec s _)) = fromEnum s

instance Real Seconds where
toRational (Seconds x) = toInteger x % s2ns

instance Fractional Seconds where
fromRational x = Seconds . fromInteger $ floor (x * s2ns)
Seconds a / Seconds b = Seconds $ a * s2ns `div` b
recip (Seconds a) = Seconds $ s2ns * s2ns `div` a

instance RealFrac Seconds where
properFraction (Seconds (TimeSpec s ns))
| s >= 0 = (fromIntegral s, Seconds $ TimeSpec 0 ns)
| otherwise = (fromIntegral (s+1), Seconds $ TimeSpec (-1) ns)
1 change: 1 addition & 0 deletions clock.cabal
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ library
ForeignFunctionInterface
ScopedTypeVariables
ViewPatterns
GeneralizedNewtypeDeriving
if os(windows)
c-sources: cbits/hs_clock_win32.c
include-dirs: cbits
Expand Down

0 comments on commit 85ecc2f

Please sign in to comment.