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
_______________________________________________
Haskell-Cafe mailing list
Haskell-Cafe@haskell.org
http://www.haskell.org/mailman/listinfo/haskell-cafe

Reply via email to