Skip to content

Commit

Permalink
quasar: Add throwing variants of readRc and duplicateRc
Browse files Browse the repository at this point in the history
  • Loading branch information
queezle42 committed May 14, 2024
1 parent 1e1d28c commit a80b056
Showing 1 changed file with 18 additions and 1 deletion.
19 changes: 18 additions & 1 deletion quasar/src/Quasar/Resources/Rc.hs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,18 @@ module Quasar.Resources.Rc (
newRcIO,
tryReadRc,
tryReadRcIO,
readRc,
readRcIO,
tryDuplicateRc,
duplicateRc,
tryExtractRc,
consumeRc,
) where

import Quasar.Prelude
import Quasar.Resources
import Quasar.Resources.DisposableVar
import Quasar.Exceptions (mkDisposedException)
import Quasar.Exceptions (mkDisposedException, DisposedException(..))
import Control.Exception (finally)

-- | A Rc is a disposable readonly data structure that can be cloned. Every copy
Expand Down Expand Up @@ -90,6 +93,14 @@ tryReadRcIO :: MonadIO m => Rc a -> m (Maybe a)
tryReadRcIO (Rc var) = liftIO do
(.content) <<$>> tryReadDisposableVarIO var

readRc :: MonadSTMc NoRetry '[DisposedException] m => Rc a -> m a
readRc rc = liftSTMc @NoRetry @'[DisposedException] do
maybe (throwC mkDisposedException) pure =<< tryReadRc rc

readRcIO :: MonadIO m => Rc a -> m a
readRcIO rc = liftIO do
maybe (throwIO mkDisposedException) pure =<< tryReadRcIO rc

-- | Produces a _new_ lock that points to the same content, but has an
-- independent lifetime. The caller has to ensure the new lock is disposed.
--
Expand All @@ -100,6 +111,12 @@ tryDuplicateRc (Rc var) = liftSTMc @NoRetry @'[] do
modifyTVar rc.lockCount succ
Rc <$> newSpecialDisposableVar decrementRc rc

duplicateRc ::
(HasCallStack, MonadSTMc NoRetry '[DisposedException] m) =>
Rc a -> m (Rc a)
duplicateRc rc = liftSTMc @NoRetry @'[DisposedException] do
maybe (throwC mkDisposedException) pure =<< tryDuplicateRc rc

consumeRc :: Rc a -> (a -> IO b) -> IO b
consumeRc rc fn = do
flip finally (dispose rc) do
Expand Down

0 comments on commit a80b056

Please sign in to comment.