aboutsummaryrefslogtreecommitdiff
path: root/src/Chelleport/Utils.hs
blob: 3f0dd733c48f56c710eb13d99f3d81d5224ac0cf (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
module Chelleport.Utils where

import Control.Monad.IO.Class (MonadIO (liftIO))
import Data.List (nub)
import Data.Time.Clock.System (SystemTime (systemNanoseconds), getSystemTime)
import qualified Debug.Trace as Debug
import Foreign.C (CInt)

intToCInt :: Int -> CInt
intToCInt = fromIntegral

cIntToInt :: CInt -> Int
cIntToInt = fromIntegral

findWithIndex :: (x -> Maybe r) -> Int -> [x] -> Maybe (Int, r)
findWithIndex _predicate _index [] = Nothing
findWithIndex predicate index (x : ls) =
  case predicate x of
    Just item -> Just (index, item)
    Nothing -> findWithIndex predicate (index + 1) ls

uniq :: (Eq a) => [a] -> [a]
uniq = nub

isEmpty :: [a] -> Bool
isEmpty = null

isNotEmpty :: [a] -> Bool
isNotEmpty = not . isEmpty

benchmark :: (MonadIO m) => String -> m a -> m a
benchmark msg m = do
  start <- systemNanoseconds <$> liftIO getSystemTime
  result <- m
  end <- systemNanoseconds <$> liftIO getSystemTime
  Debug.traceM $ msg ++ " (ms): " ++ show (fromIntegral (end - start) / 1_000_000.0 :: Double)
  pure result

itemAt :: [a] -> Int -> Maybe a
itemAt [] _ = Nothing
itemAt (x : _) 0 = Just x
itemAt (_ : xs) i = itemAt xs (i - 1)

clamp :: (Integral a) => (a, a) -> a -> a
clamp (low, high) n = max low (min high n)

(<&&>) :: [a -> Bool] -> a -> Bool
(<&&>) preds ev = all (\p -> p ev) preds

(<||>) :: (a -> Bool) -> (a -> Bool) -> a -> Bool
(<||>) p1 p2 x = p1 x || p2 x