----------------------------------------------------------------------------
-- |
-- Module      :  Data.Emacs.Module.NonNullPtr
-- Copyright   :  (c) Sergey Vinokurov 2018
-- License     :  Apache-2.0 (see LICENSE)
-- Maintainer  :  serg.foo@gmail.com
----------------------------------------------------------------------------

{-# LANGUAGE CPP #-}

module Data.Emacs.Module.NonNullPtr
  ( NonNullPtr
  , unNonNullPtr
  , mkNonNullPtr
  , allocaNonNull
  , allocaBytesNonNull
  ) where

import Foreign

import Data.Emacs.Module.NonNullPtr.Internal
import Emacs.Module.Assert

mkNonNullPtr :: WithCallStack => Ptr a -> NonNullPtr a
#ifdef ASSERTIONS
mkNonNullPtr x
  | x == nullPtr = error "Assertion failed: trying to make non-null pointer from a null one"
  | otherwise    = NonNullPtr x
#else
mkNonNullPtr :: Ptr a -> NonNullPtr a
mkNonNullPtr = Ptr a -> NonNullPtr a
forall a. Ptr a -> NonNullPtr a
NonNullPtr
#endif

{-# INLINE allocaNonNull #-}
allocaNonNull :: Storable a => (NonNullPtr a -> IO b) -> IO b
allocaNonNull :: (NonNullPtr a -> IO b) -> IO b
allocaNonNull NonNullPtr a -> IO b
f = (Ptr a -> IO b) -> IO b
forall a b. Storable a => (Ptr a -> IO b) -> IO b
alloca (NonNullPtr a -> IO b
f (NonNullPtr a -> IO b) -> (Ptr a -> NonNullPtr a) -> Ptr a -> IO b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Ptr a -> NonNullPtr a
forall a. Ptr a -> NonNullPtr a
NonNullPtr)

{-# INLINE allocaBytesNonNull #-}
allocaBytesNonNull :: Int -> (NonNullPtr a -> IO b) -> IO b
allocaBytesNonNull :: Int -> (NonNullPtr a -> IO b) -> IO b
allocaBytesNonNull Int
n NonNullPtr a -> IO b
f = Int -> (Ptr a -> IO b) -> IO b
forall a b. Int -> (Ptr a -> IO b) -> IO b
allocaBytes Int
n (NonNullPtr a -> IO b
f (NonNullPtr a -> IO b) -> (Ptr a -> NonNullPtr a) -> Ptr a -> IO b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Ptr a -> NonNullPtr a
forall a. Ptr a -> NonNullPtr a
NonNullPtr)