blob: 80e4914d4c4751f6bf88d17472408305bbc1dd9d [file] [log] [blame]
Bryan Duxbury0781f2b2009-04-07 23:29:42 +00001--
2-- Licensed to the Apache Software Foundation (ASF) under one
3-- or more contributor license agreements. See the NOTICE file
4-- distributed with this work for additional information
5-- regarding copyright ownership. The ASF licenses this file
6-- to you under the Apache License, Version 2.0 (the
7-- "License"); you may not use this file except in compliance
8-- with the License. You may obtain a copy of the License at
9--
10-- http://www.apache.org/licenses/LICENSE-2.0
11--
12-- Unless required by applicable law or agreed to in writing,
13-- software distributed under the License is distributed on an
14-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15-- KIND, either express or implied. See the License for the
16-- specific language governing permissions and limitations
17-- under the License.
18--
19
20module Thrift.Transport
21 ( Transport(..)
22 , TransportExn(..)
23 , TransportExnType(..)
24 ) where
25
26import Control.Monad ( when )
27import Control.Exception ( Exception, throw )
28
29import Data.Typeable ( Typeable )
30
David Reiss752529e2010-01-11 19:12:56 +000031import qualified Data.ByteString.Lazy.Char8 as LBS
32import Data.Monoid
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000033
34class Transport a where
35 tIsOpen :: a -> IO Bool
36 tClose :: a -> IO ()
David Reiss752529e2010-01-11 19:12:56 +000037 tRead :: a -> Int -> IO LBS.ByteString
38 tWrite :: a -> LBS.ByteString -> IO ()
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000039 tFlush :: a -> IO ()
David Reiss752529e2010-01-11 19:12:56 +000040 tReadAll :: a -> Int -> IO LBS.ByteString
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000041
David Reiss752529e2010-01-11 19:12:56 +000042 tReadAll a 0 = return mempty
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000043 tReadAll a len = do
44 result <- tRead a len
David Reiss752529e2010-01-11 19:12:56 +000045 let rlen = fromIntegral $ LBS.length result
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000046 when (rlen == 0) (throw $ TransportExn "Cannot read. Remote side has closed." TE_UNKNOWN)
47 if len <= rlen
48 then return result
David Reiss752529e2010-01-11 19:12:56 +000049 else (result `mappend`) `fmap` (tReadAll a (len - rlen))
Bryan Duxbury0781f2b2009-04-07 23:29:42 +000050
51data TransportExn = TransportExn String TransportExnType
52 deriving ( Show, Typeable )
53instance Exception TransportExn
54
55data TransportExnType
56 = TE_UNKNOWN
57 | TE_NOT_OPEN
58 | TE_ALREADY_OPEN
59 | TE_TIMED_OUT
60 | TE_END_OF_FILE
61 deriving ( Eq, Show, Typeable )
62