module Network.HTTP2.Arch.Rate (
    Rate
  , newRate
  , getRate
  ) where

import Data.IORef
import Data.UnixTime

newtype Rate = Rate (IORef Counter)

data Counter = Counter Int UnixTime

newRate :: IO Rate
newRate :: IO Rate
newRate = do
    Counter
cntr <- Int -> UnixTime -> Counter
Counter Int
0 forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO UnixTime
getUnixTime
    IORef Counter -> Rate
Rate forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> forall a. a -> IO (IORef a)
newIORef Counter
cntr

getRate :: Rate -> IO Int
getRate :: Rate -> IO Int
getRate (Rate IORef Counter
ref) = do
    Counter Int
n UnixTime
beg <- forall a. IORef a -> IO a
readIORef IORef Counter
ref
    UnixTime
cur <- IO UnixTime
getUnixTime
    if (UnixTime
cur UnixTime -> UnixTime -> UnixDiffTime
`diffUnixTime` UnixTime
beg) forall a. Ord a => a -> a -> Bool
> UnixDiffTime
1 then do
        let n' :: Int
n' = Int
1
        forall a. IORef a -> a -> IO ()
writeIORef IORef Counter
ref forall a b. (a -> b) -> a -> b
$ Int -> UnixTime -> Counter
Counter Int
n' UnixTime
cur
        forall (m :: * -> *) a. Monad m => a -> m a
return Int
n'
      else do
        let n' :: Int
n' = Int
n forall a. Num a => a -> a -> a
+ Int
1
        forall a. IORef a -> a -> IO ()
writeIORef IORef Counter
ref forall a b. (a -> b) -> a -> b
$ Int -> UnixTime -> Counter
Counter Int
n' UnixTime
beg
        forall (m :: * -> *) a. Monad m => a -> m a
return Int
n'