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 #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
24 #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
29 /// Foundation-less Swift File transport.
30 /// Uses C fopen/fread/fwrite,
31 /// provided by Glibc in linux and Darwin on OSX/iOS
32 public class TFileTransport: TTransport {
33 var fileHandle: UnsafeMutablePointer<FILE>? = nil
35 public init (fileHandle: UnsafeMutablePointer<FILE>) {
36 self.fileHandle = fileHandle
39 public convenience init(filename: String) throws {
40 var fileHandle: UnsafeMutablePointer<FILE>?
41 filename.withCString({ cFilename in
42 "rw".withCString({ cMode in
43 fileHandle = fopen(cFilename, cMode)
46 if let fileHandle = fileHandle {
47 self.init(fileHandle: fileHandle)
49 throw TTransportError(error: .notOpen)
54 fclose(self.fileHandle)
57 public func readAll(size: Int) throws -> Data {
58 let read = try self.read(size: size)
60 if read.count != size {
61 throw TTransportError(error: .endOfFile)
66 public func read(size: Int) throws -> Data {
67 // set up read buffer, position 0
68 var read = Data(capacity: size)
71 // read character buffer
72 var nextChar: UInt8 = 0
74 // continue until we've read size bytes
75 while read.count < size {
76 if fread(&nextChar, 1, 1, self.fileHandle) == 1 {
77 read[position] = nextChar
79 // Increment output byte pointer
83 throw TTransportError(error: .endOfFile)
89 public func write(data: Data) throws {
90 let bytesWritten = data.withUnsafeBytes {
91 fwrite($0, 1, data.count, self.fileHandle)
93 if bytesWritten != data.count {
94 throw TTransportError(error: .unknown)
98 public func flush() throws {