Skip to content

Commit 47f3f93

Browse files
committed
Added an implementation for NSPipe
The implementation itself is very simple. In the unlikely event that the `pipe` system call fails, this implementation will stop with a fatalError. This seems to be the canon way of doing it based on my cursory reading of the rest of foundation.
1 parent 4a6d90f commit 47f3f93

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

Foundation/NSFileHandle.swift

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -321,15 +321,35 @@ extension NSFileHandle {
321321

322322
public class NSPipe : NSObject {
323323

324+
private let readHandle: NSFileHandle
325+
private let writeHandle: NSFileHandle
326+
324327
public override init() {
328+
/// the `pipe` system call creates two `fd` in a malloc'ed area
329+
var fds = UnsafeMutablePointer<Int32>.alloc(2)
330+
defer {
331+
free(fds)
332+
}
333+
/// If the operating system prevents us from creating file handles, stop
334+
guard pipe(fds) == 0 else { fatalError("Could not open pipe file handles") }
335+
336+
/// The handles below auto-close when the `NSFileHandle` is deallocated, so we
337+
/// don't need to add a `deinit` to this class
338+
339+
/// Create the read handle from the first fd in `fds`
340+
self.readHandle = NSFileHandle(fileDescriptor: fds.memory, closeOnDealloc: true)
341+
342+
/// Advance `fds` by one to create the write handle from the second fd
343+
self.writeHandle = NSFileHandle(fileDescriptor: fds.successor().memory, closeOnDealloc: true)
325344

345+
super.init()
326346
}
327347

328348
public var fileHandleForReading: NSFileHandle {
329-
NSUnimplemented()
349+
return self.readHandle
330350
}
331-
351+
332352
public var fileHandleForWriting: NSFileHandle {
333-
NSUnimplemented()
353+
return self.writeHandle
334354
}
335355
}

0 commit comments

Comments
 (0)