Skip to content

Conversation

ocharles
Copy link
Member

No description provided.

@sheaf
Copy link
Contributor

sheaf commented Jan 27, 2021

Re: the issue with leaking memory, is the following of any use?

data ResourceVar a =
  ResourceVar
    { freeTVar :: TVar ( IO () )
    , getter   :: IO a
    , setter   :: a -> IO ( IO () )
    }

instance HasGetter ( ResourceVar a ) a where
  get ( ResourceVar { getter } ) = liftIO getter

class HasSetter t a | t -> a where
  ($=) :: MonadResource m => t -> a -> m ()

instance {-# OVERLAPPABLE #-} StateVar.HasSetter t a => HasSetter t a where
 ($=) = (StateVar.$=)

instance HasSetter ( ResourceVar a ) a where
( ResourceVar { freeTVar, setter } ) $= a = do
  freeResource <- liftIO . atomically $ swapTVar freeTVar ( pure () )
  ( key, _ ) <- allocate ( setter a ) id
  liftIO freeResource
  liftIO . atomically $ modifyTVar freeTVar ( *> release key )


{-# NOINLINE iniFilenameTVar #-}
iniFilenameTVar :: TVar ( IO () )
iniFilenameTVar = unsafePerformIO ( newTVarIO ( pure () ) )

iniFilename :: ResourceVar ( Maybe String )
iniFilename = ResourceVar { freeTVar = iniFilenameTVar, getter, setter }
  where
    getter = do
      cStr <- [C.exp| const char* { GetIO().IniFilename } |]
      if cStr == nullPtr then return Nothing else Just <$> peekCString cStr

    setter = \case
      Nothing ->
        [C.block| void { GetIO().IniFilename = $(char* nullPtr); } |]
        pure ( pure () )

      Just str -> do
        strPtr <- newCString str
        [C.block| void { GetIO().IniFilename = $(char* strPtr); } |]
        pure ( free strPtr )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants