packages feed

netlines-1.0.0: Data/Enumerator/NetLines/Class.hs

-- |
-- Module:     Data.Enumerator.NetLines.Class
-- Copyright:  (c) 2011 Ertugrul Soeylemez
-- License:    BSD3
-- Maintainer: Ertugrul Soeylemez <es@ertes.de>
--
-- Class for splittable stream types.

module Data.Enumerator.NetLines.Class
    ( -- * Splittable stream class
      Splittable(..)
    )
    where

import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as BC
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import Data.ByteString (ByteString)
import Data.Text (Text)
import System.IO


-- | This is a type class for splittable streams.  Instances provide
-- support for efficient non-blocking reading and splitting.

class Splittable str where
    append  :: str -> str -> str
    break   :: (Char -> Bool) -> str -> (str, str)
    empty   :: str
    filter  :: (Char -> Bool) -> str -> str
    null    :: str -> Bool
    tail    :: str -> str
    take    :: Int -> str -> str

    hGetNonBlocking :: Handle -> Int -> IO str
    hPutStr         :: Handle -> str -> IO ()


instance Splittable ByteString where
    append    = B.append
    break     = BC.break
    empty     = B.empty
    filter    = BC.filter
    null      = B.null
    tail      = B.tail
    take      = B.take

    hGetNonBlocking = B.hGetNonBlocking
    hPutStr         = B.hPutStr


instance Splittable Text where
    append    = T.append
    break     = T.break
    empty     = T.empty
    filter    = T.filter
    null      = T.null
    tail      = T.tail
    take      = T.take

    hGetNonBlocking h = fmap T.decodeUtf8 . B.hGetNonBlocking h
    hPutStr h = B.hPutStr h . T.encodeUtf8