packages feed

dear-imgui-raw-1.0.0: src/DearImGui/Impl/Init.hs

-- | Shared init-or-fail bracket for the backend bridge modules.
module DearImGui.Impl.Init
  ( InitFailed (..)
  , withInitOrFail
  ) where

import Control.Exception (Exception, throwIO)
import Control.Monad (unless)
import Control.Monad.IO.Unlift (MonadUnliftIO)
import Data.Text (Text)

import DearImGui.Bracket (withCreated)

-- | The named backend entry point returned false.
newtype InitFailed = InitFailed Text
  deriving (Show)

instance Exception InitFailed

{- | Run the body between an init that must succeed and the matching
shutdown; an init returning 'False' throws 'InitFailed' with the C entry
point name instead of running the body.
-}
withInitOrFail :: (MonadUnliftIO m) => Text -> IO Bool -> IO () -> m a -> m a
withInitOrFail name doInit doShutdown =
  withCreated acquire (const doShutdown)
  where
    acquire = do
      ok <- doInit
      unless ok (throwIO (InitFailed name))