Last active
February 8, 2016 18:53
-
-
Save russbishop/e4cbc3d498b22f335b8a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Working around Foundation deficiencies when trying to append to a file | |
// (and without run loops, delegates, and other BS). | |
// Why is this so complicated? | |
import Foundation | |
public final class TemporaryFile { | |
public let handle: NSFileHandle //IUO until Swift 2.2 | |
public let url: NSURL | |
/// Creates a temporary file with a random name in the given directory | |
public init(inDirectory: NSURL) throws { | |
self.url = inDirectory.URLByAppendingPathComponent(NSUUID().UUIDString) | |
let data = NSData() | |
do { | |
try data.writeToURL(self.url, options: NSDataWritingOptions()) | |
self.handle = try NSFileHandle(forWritingToURL: self.url) | |
} catch { | |
self.handle = NSFileHandle() | |
throw error | |
} | |
} | |
/// Creates a temporary file with a random name in the temporary files directory | |
public convenience init() throws { | |
try self.init(inDirectory: NSURL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)) | |
} | |
public func write(data: NSData) { | |
self.handle.writeData(data) | |
} | |
public func write(buffer: [UInt8]) { | |
buffer.withUnsafeBufferPointer { (ptr) -> Void in | |
let data = NSData(bytes: UnsafePointer<Void>(ptr.baseAddress), length: ptr.count) | |
self.write(data) | |
} | |
} | |
public func moveTo(destination: NSURL) throws { | |
try NSFileManager.defaultManager().moveItemAtURL(self.url, toURL: destination) | |
} | |
/// Returns a memory-mapped `NSData` of the file contents. Used for testing. | |
public func read() throws -> NSData { | |
return try NSData(contentsOfURL: self.url, options: NSDataReadingOptions.DataReadingMappedIfSafe) | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment