]>
Commit | Line | Data |
---|---|---|
f67539c2 TL |
1 | /* |
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 | ||
20 | import Foundation | |
21 | ||
22 | public class TMemoryBufferTransport : TTransport { | |
23 | public private(set) var readBuffer = Data() | |
24 | public private(set) var writeBuffer = Data() | |
25 | ||
26 | public private(set) var position = 0 | |
27 | ||
28 | public var bytesRemainingInBuffer: Int { | |
29 | return readBuffer.count - position | |
30 | } | |
31 | ||
32 | public func consumeBuffer(size: Int) { | |
33 | position += size | |
34 | } | |
35 | public func clear() { | |
36 | readBuffer = Data() | |
37 | writeBuffer = Data() | |
38 | } | |
39 | ||
40 | ||
41 | private var flushHandler: ((TMemoryBufferTransport, Data) -> ())? | |
42 | ||
43 | public init(flushHandler: ((TMemoryBufferTransport, Data) -> ())? = nil) { | |
44 | self.flushHandler = flushHandler | |
45 | } | |
46 | ||
47 | public convenience init(readBuffer: Data, flushHandler: ((TMemoryBufferTransport, Data) -> ())? = nil) { | |
48 | self.init() | |
49 | self.readBuffer = readBuffer | |
50 | } | |
51 | ||
52 | public func reset(readBuffer: Data = Data(), writeBuffer: Data = Data()) { | |
53 | self.readBuffer = readBuffer | |
54 | self.writeBuffer = writeBuffer | |
55 | } | |
56 | ||
57 | public func read(size: Int) throws -> Data { | |
58 | let amountToRead = min(bytesRemainingInBuffer, size) | |
59 | if amountToRead > 0 { | |
60 | let ret = readBuffer.subdata(in: Range(uncheckedBounds: (lower: position, upper: position + amountToRead))) | |
61 | position += ret.count | |
62 | return ret | |
63 | } | |
64 | return Data() | |
65 | } | |
66 | ||
67 | public func write(data: Data) throws { | |
68 | writeBuffer.append(data) | |
69 | } | |
70 | ||
71 | public func flush() throws { | |
72 | flushHandler?(self, writeBuffer) | |
73 | } | |
74 | } |