module SocketActivation.GetFileDescriptors where

import Control.Monad (Monad (return, (>>=)))
import Data.Either (Either)
import Data.Function ((.))
import Data.Int (Int)
import Data.List (take)
import Numeric.Natural (Natural)
import Prelude (fromIntegral)
import System.IO (IO)

import SocketActivation.Concepts (Fd (..), Error, Count (countNat))
import SocketActivation.Env (getEnv')
import SocketActivation.IO (IO' (IO', run))

{-| Get a list of file descriptors for the sockets -}
getFileDescriptorList :: IO (Either Error [Fd])
getFileDescriptorList :: IO (Either Error [Fd])
getFileDescriptorList = forall a. IO' a -> IO (Either Error a)
run (IO' Count
getCount forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Count -> IO' [Fd]
enumerateFds)
  where
    getCount :: IO' Count
getCount = forall a. IO (Either Error a) -> IO' a
IO' (forall a. Env' a => IO (Either Error a)
getEnv' @Count)
    enumerateFds :: Count -> IO' [Fd]
enumerateFds = forall (m :: * -> *) a. Monad m => a -> m a
return forall b c a. (b -> c) -> (a -> b) -> a -> c
. Count -> [Fd]
fds

fds :: Count -> [Fd]
fds :: Count -> [Fd]
fds Count
n = forall a. Int -> [a] -> [a]
take (Count -> Int
convert Count
n) [Fd
firstFd ..]
  where
    convert :: Count -> Int
convert = (forall a b. (Integral a, Num b) => a -> b
fromIntegral :: Natural -> Int) forall b c a. (b -> c) -> (a -> b) -> a -> c
. Count -> Natural
countNat
    firstFd :: Fd
firstFd = CInt -> Fd
Fd CInt
3