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
10 -- http://www.apache.org/licenses/LICENSE-2.0
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
20 module Thrift.Transport.Memory
25 import Data.ByteString.Lazy.Builder
29 import qualified Data.ByteString.Lazy as LBS
31 import Thrift.Transport
34 data MemoryBuffer = MemoryBuffer {
35 writeBuffer :: IORef Builder,
36 readBuffer :: IORef LBS.ByteString
39 openMemoryBuffer :: IO MemoryBuffer
41 wbuf <- newIORef mempty
42 rbuf <- newIORef mempty
48 instance Transport MemoryBuffer where
49 tIsOpen = const $ return False
50 tClose = const $ return ()
52 let wBuf = writeBuffer trans
54 modifyIORef (readBuffer trans) $ \rb -> mappend rb $ toLazyByteString wb
55 writeIORef wBuf mempty
57 tRead _ 0 = return mempty
59 let rbuf = readBuffer trans
61 let len = fromIntegral $ LBS.length rb
65 rb2 <- readIORef (readBuffer trans)
66 if (fromIntegral $ LBS.length rb2) == 0
70 let (ret, remain) = LBS.splitAt (fromIntegral n) rb
71 writeIORef rbuf remain
74 tPeek trans = (fmap fst . LBS.uncons) <$> readIORef (readBuffer trans)
77 modifyIORef (writeBuffer trans) (<> lazyByteString v)