module PureSAT.Utils where

import Control.Monad.ST (ST)
import Data.Bits
import Data.STRef (STRef, readSTRef)

whenOk :: STRef s Bool -> ST s Bool -> ST s Bool
whenOk :: forall s. STRef s Bool -> ST s Bool -> ST s Bool
whenOk STRef s Bool
ok = ST s Bool -> ST s Bool -> ST s Bool
forall s. ST s Bool -> ST s Bool -> ST s Bool
whenOk_ (STRef s Bool -> ST s Bool
forall s a. STRef s a -> ST s a
readSTRef STRef s Bool
ok)

whenOk_ :: ST s Bool -> ST s Bool -> ST s Bool
whenOk_ :: forall s. ST s Bool -> ST s Bool -> ST s Bool
whenOk_ ST s Bool
ok ST s Bool
action = do
    Bool
ok' <- ST s Bool
ok
    if Bool
ok' then ST s Bool
action else Bool -> ST s Bool
forall a. a -> ST s a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False

-- | Next power of two.
--
-- >>> map nextPowerOf2 [-1, 0, 1, 2, 1024, 1245, 9999]
-- [1,1,1,2,1024,2048,16384]
--
nextPowerOf2 :: Int -> Int
nextPowerOf2 :: Int -> Int
nextPowerOf2 Int
n
    | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
1    = Int
1
    | Bool
otherwise = Int -> Int -> Int
forall a. Bits a => a -> Int -> a
unsafeShiftL Int
1 (Int -> Int
forall b. FiniteBits b => b -> Int
finiteBitSize (Int
0 :: Int) Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int -> Int
forall b. FiniteBits b => b -> Int
countLeadingZeros (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1))