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
22 public class TMemoryBufferTransport : TTransport {
23 public private(set) var readBuffer = Data()
24 public private(set) var writeBuffer = Data()
26 public private(set) var position = 0
28 public var bytesRemainingInBuffer: Int {
29 return readBuffer.count - position
32 public func consumeBuffer(size: Int) {
41 private var flushHandler: ((TMemoryBufferTransport, Data) -> ())?
43 public init(flushHandler: ((TMemoryBufferTransport, Data) -> ())? = nil) {
44 self.flushHandler = flushHandler
47 public convenience init(readBuffer: Data, flushHandler: ((TMemoryBufferTransport, Data) -> ())? = nil) {
49 self.readBuffer = readBuffer
52 public func reset(readBuffer: Data = Data(), writeBuffer: Data = Data()) {
53 self.readBuffer = readBuffer
54 self.writeBuffer = writeBuffer
57 public func read(size: Int) throws -> Data {
58 let amountToRead = min(bytesRemainingInBuffer, size)
60 let ret = readBuffer.subdata(in: Range(uncheckedBounds: (lower: position, upper: position + amountToRead)))
67 public func write(data: Data) throws {
68 writeBuffer.append(data)
71 public func flush() throws {
72 flushHandler?(self, writeBuffer)