-----------------------------------------------------------
-- |
-- Module      : Control.Imperative.Var.Class
-- Copyright   : (C) 2015, Yu Fukuzawa
-- License     : BSD3
-- Maintainer  : minpou.primer@email.com
-- Stability   : experimental
-- Portability : portable
--
-----------------------------------------------------------

{-# LANGUAGE TypeFamilies #-}

module Control.Imperative.Var.Class
( -- * Class
  MVar(..)
) where

import           Control.Monad.ST
import           Data.IORef
import           Data.STRef

-- | Base class for mutable variables.
class Monad m => MVar m where
  type VarEntity m :: * -> *
  newVar :: a -> m (VarEntity m a)
  readVar  :: VarEntity m a -> m a
  writeVar :: VarEntity m a -> a -> m ()

instance MVar IO where
  type VarEntity IO = IORef
  newVar = newIORef
  {-# INLINE newVar #-}
  readVar = readIORef
  {-# INLINE readVar #-}
  writeVar = writeIORef
  {-# INLINE writeVar #-}

instance MVar (ST s) where
  type VarEntity (ST s) = STRef s
  newVar = newSTRef
  {-# INLINE newVar #-}
  readVar = readSTRef
  {-# INLINE readVar #-}
  writeVar = writeSTRef
  {-# INLINE writeVar #-}