[Haskell-cafe] Re: DevRandom

Bryan Donlan bd.haskell at uguu.us
Tue Jan 30 14:37:22 EST 2007


Yitzchak Gale wrote:
> It's short, so I'll post it here.
> Any comments?

> readDev :: Storable a => FilePath -> BlockingMode -> IO (Maybe a)
> readDev dev mode = do
>    h <- openFile dev ReadMode
>    hSetBuffering h NoBuffering
>    alloca $ getMaybe h undefined
>  where
>    getMaybe :: Storable a => Handle -> a -> Ptr a -> IO (Maybe a)
>    getMaybe h undef ptr = do
>      let size = sizeOf undef
>      n <- case mode of
>             Blocking    -> hGetBuf            h ptr size
>             NonBlocking -> hGetBufNonBlocking h ptr size
>      if n < size
>        then return Nothing
>        else peek ptr >>= return . Just

This re-opens the device every time we need it. How about opening once, 
when it's first needed?

hDevRandom :: Handle
{-# NOINLINE hDevRandom  #-}
hDevRandom = unsafePerformIO $ openFile "/dev/random" ReadMode

hDevURandom :: Handle
{-# NOINLINE hDevURandom  #-}
hDevURandom = unsafePerformIO $ openFile "/dev/urandom" ReadMode


More information about the Haskell-Cafe mailing list