blob: 78b2f5cf0f584e1b9fa9904a410972646cd7c055 [file] [log] [blame]
Roger Meier6cf0ffc2014-04-05 00:45:42 +02001--
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
20require 'TTransport'
21
22TMemoryBuffer = TTransportBase:new{
23 __type = 'TMemoryBuffer',
24 buffer = '',
25 bufferSize = 1024,
26 wPos = 0,
27 rPos = 0
28}
29function TMemoryBuffer:isOpen()
30 return 1
31end
32function TMemoryBuffer:open() end
33function TMemoryBuffer:close() end
34
35function TMemoryBuffer:peak()
36 return self.rPos < self.wPos
37end
38
39function TMemoryBuffer:getBuffer()
40 return self.buffer
41end
42
43function TMemoryBuffer:resetBuffer(buf)
44 if buf then
45 self.buffer = buf
46 self.bufferSize = string.len(buf)
47 else
48 self.buffer = ''
49 self.bufferSize = 1024
50 end
51 self.wPos = string.len(buf)
52 self.rPos = 0
53end
54
55function TMemoryBuffer:available()
56 return self.wPos - self.rPos
57end
58
59function TMemoryBuffer:read(len)
60 local avail = self:available()
61 if avail == 0 then
62 return ''
63 end
64
65 if avail < len then
66 len = avail
67 end
68
winsweet38a1c662014-12-08 15:51:45 +080069 local val = string.sub(self.buffer, self.rPos + 1, self.rPos + len)
Roger Meier6cf0ffc2014-04-05 00:45:42 +020070 self.rPos = self.rPos + len
71 return val
72end
73
74function TMemoryBuffer:readAll(len)
75 local avail = self:available()
76
77 if avail < len then
78 local msg = string.format('Attempt to readAll(%d) found only %d available',
79 len, avail)
80 terror(TTransportException:new{message = msg})
81 end
82 -- read should block so we don't need a loop here
83 return self:read(len)
84end
85
86function TMemoryBuffer:write(buf)
winsweet38a1c662014-12-08 15:51:45 +080087 self.buffer = self.buffer .. buf
88 self.wPos = self.wPos + string.len(buf)
Roger Meier6cf0ffc2014-04-05 00:45:42 +020089end
90
91function TMemoryBuffer:flush() end