-- {-# LANGUAGE OverloadedStrings #-}
-- {-# LANGUAGE ExistentialQuantification #-}
-- {-# LANGUAGE ForeignFunctionInterface #-}
-- {-# LANGUAGE InterruptibleFFI #-}
-- {-# LANGUAGE EmptyDataDecls #-}

module System.IO.Uniform.Std (
  StdIO
  ) where

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

import Foreign
--import Foreign.C.Types
--import Foreign.C.String
import Foreign.C.Error
--import qualified Data.IP as IP
--import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
--import qualified Data.ByteString.Lazy as LBS
--import qualified Data.ByteString.Builder as BSBuild
--import qualified Data.List as L
--import Control.Exception
--import Control.Applicative ((<$>))
--import Data.Monoid (mappend)
--import qualified Network.Socket as Soc
--import System.IO.Error
--import Control.Concurrent.MVar

--import Data.Default.Class

--import System.Posix.Types (Fd(..))
-- | UniformIO that reads from stdin and writes to stdout.
instance UniformIO StdIO where
  uRead _ n = do
    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 = do
    BS.useAsCStringLen t (
      \(str, n) -> do
        count <- c_sendStd str $ fromIntegral n
        if count < 0
          then throwErrno "could not write"
          else return ()
      )
  uClose _ = return ()
  startTls _ _ = return . TlsIO $ nullPtr
  isSecure _ = False