Created
December 11, 2015 21:44
-
-
Save zwaldowski/ddbdffa58e4d005db03b 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
public final class StaticCStringArray { | |
private let storage: AnyForwardCollection<StaticString> | |
private lazy var pointers: ContiguousArray<UnsafeMutablePointer<Int8>> = { | |
ContiguousArray(self.storage.lazy.map { UnsafeMutablePointer($0.utf8Start) }) | |
}() | |
init<Collection: CollectionType where Collection.Generator.Element == StaticString>(_ strings: Collection) { | |
self.storage = AnyForwardCollection(strings) | |
} | |
func withPointerToStrings<Return>(@noescape body: UnsafePointer<UnsafeMutablePointer<Int8>> throws -> Return) rethrows -> Return { | |
return try pointers.withUnsafeBufferPointer { | |
try body($0.baseAddress) | |
} | |
} | |
} | |
public struct CStringArray { | |
private let storage: ContiguousArray<ContiguousArray<UInt8>> | |
init<Sequence: SequenceType where Sequence.Generator.Element == String>(_ strings: Sequence) { | |
self.storage = ContiguousArray(strings.lazy.map { $0.nulTerminatedUTF8 }) | |
} | |
func withPointerToStrings<Return>(@noescape body: UnsafePointer<UnsafeMutablePointer<Int8>> throws -> Return) rethrows -> Return { | |
return try withExtendedLifetime(storage) { () -> Return in | |
let pointers = storage.map { arrays in | |
arrays.withUnsafeBufferPointer { UnsafeMutablePointer<Int8>($0.baseAddress) } | |
} | |
return try pointers.withUnsafeBufferPointer { | |
try body($0.baseAddress) | |
} | |
} | |
} | |
} | |
var f = StaticCStringArray([ "-f", "a", "-b", "c" ]) | |
f.withPointerToStrings { | |
String.fromCString(UnsafePointer($0[0])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment