-- | UniformIO over stdin and stdout
module System.IO.Uniform.Std (
  StdIO(StdIO)
  ) where

import System.IO.Uniform
import System.IO.Uniform.External

import Foreign
import Foreign.C.Error
import qualified Data.ByteString as BS
import Control.Monad

-- | UniformIO that reads from stdin and writes to stdout.
instance UniformIO StdIO where
  uRead _ n = allocaArray n (
    \b -> do
      count <- c_recvStd b (fromIntegral n)
      if count < 0
        then throwErrno "could not read"
        else BS.packCStringLen (b, fromIntegral count)
    )
  uPut _ t = BS.useAsCStringLen t (
    \(str, n) -> do
      count <- c_sendStd str $ fromIntegral n
      when (count < 0) $ throwErrno "could not write"
    )
  uClose _ = return ()
  startTls _ = return
  isSecure _ = True