Skip to content

Implement FileHandle.nullDevice #690

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 10, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 41 additions & 3 deletions Foundation/NSFileHandle.swift
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -214,11 +214,49 @@ extension FileHandle {
open class var standardError: FileHandle {
return _stderrFileHandle
}


internal static var _nulldeviceFileHandle: FileHandle = {
class NullDevice: FileHandle {
override var availableData: Data {
return Data()
}

override func readDataToEndOfFile() -> Data {
return Data()
}

override func readData(ofLength length: Int) -> Data {
return Data()
}

override func write(_ data: Data) {}

override var offsetInFile: UInt64 {
return 0
}

override func seekToEndOfFile() -> UInt64 {
return 0
}

override func seek(toFileOffset offset: UInt64) {}

override func truncateFile(atOffset offset: UInt64) {}

override func synchronizeFile() {}

override func closeFile() {}

deinit {}
}

return NullDevice(fileDescriptor: -1, closeOnDealloc: false)
}()

open class var nullDevice: FileHandle {
NSUnimplemented()
return _nulldeviceFileHandle
}

public convenience init?(forReadingAtPath path: String) {
self.init(path: path, flags: O_RDONLY, createMode: 0)
}
Expand Down
20 changes: 20 additions & 0 deletions TestFoundation/TestNSFileHandle.swift
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ class TestNSFileHandle : XCTestCase {
static var allTests : [(String, (TestNSFileHandle) -> () throws -> ())] {
return [
("test_pipe", test_pipe),
("test_nullDevice", test_nullDevice),
]
}

Expand All @@ -38,4 +39,23 @@ class TestNSFileHandle : XCTestCase {
XCTAssertEqual(output, input)
}
}

func test_nullDevice() {
let fh = FileHandle.nullDevice

XCTAssertEqual(fh.fileDescriptor, -1)
fh.closeFile()
fh.seek(toFileOffset: 10)
XCTAssertEqual(fh.offsetInFile, 0)
XCTAssertEqual(fh.seekToEndOfFile(), 0)
XCTAssertEqual(fh.readData(ofLength: 15).count, 0)
fh.synchronizeFile()

fh.write(Data(bytes: [1,2]))
fh.seek(toFileOffset: 0)
XCTAssertEqual(fh.availableData.count, 0)
fh.write(Data(bytes: [1,2]))
fh.seek(toFileOffset: 0)
XCTAssertEqual(fh.readDataToEndOfFile().count, 0)
}
}