Created
December 1, 2015 21:59
-
-
Save jepers/39b47f269911d5e1cc81 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
protocol DefaultInitializable { init() } | |
protocol StaticStorageType : DefaultInitializable { | |
typealias Element: DefaultInitializable = Self | |
static var staticCount: Int { get } | |
} | |
extension StaticStorageType { | |
typealias Plus1 = StaticStorageOfOneMoreThan<Self> | |
typealias Plus2 = Plus1.Plus1 | |
typealias Plus3 = Plus2.Plus1 | |
typealias Times2 = StaticStorageDoubled<Self> | |
typealias Times4 = Times2.Times2 | |
typealias Times8 = Times4.Times2 | |
typealias Times16 = Times8.Times2 | |
typealias Times32 = Times16.Times2 | |
static var staticCount: Int { return 1 } | |
var count: Int { return Self.staticCount } | |
var indices: Range<Int> { return 0 ..< count } | |
subscript(i: Int) -> Element { | |
get { precondition(0 <= i && i < count) | |
var selfCopy = self | |
return withUnsafePointer(&selfCopy, { p -> Element in UnsafePointer<Element>(p)[i] }) | |
} | |
set { precondition(0 <= i && i < count) | |
withUnsafeMutablePointer(&self, { p -> Void in UnsafeMutablePointer<Element>(p)[i] = newValue }) | |
} | |
} | |
} | |
struct StaticStorageOfOne<T: StaticStorageType> : StaticStorageType { | |
typealias Element = T | |
let _storage = Element() | |
} | |
struct StaticStorageOfOneMoreThan<T: StaticStorageType> : StaticStorageType { | |
typealias Element = T.Element | |
let _storage = (Element(), T()) | |
static var staticCount: Int { return T.staticCount + 1 } | |
} | |
struct StaticStorageDoubled<T: StaticStorageType> : StaticStorageType { | |
typealias Element = T.Element | |
let _storage = (T(), T()) | |
static var staticCount: Int { return T.staticCount * 2 } | |
} | |
extension UInt8 : StaticStorageType {} | |
extension Float : StaticStorageType {} | |
typealias _128_Bytes = UInt8.Times32.Times4 | |
typealias _11_Floats = Float.Times8.Plus3 | |
print(strideof(_128_Bytes)) // Prints 128 | |
print(strideof(_11_Floats)) // Prints 44 ( 44 == 11 * 4 ) | |
var myThreeFloats = Float.Plus2() | |
myThreeFloats[0] = 0.1 | |
myThreeFloats[1] = 1.2 | |
myThreeFloats[2] = 3.4 | |
for i in myThreeFloats.indices { print(myThreeFloats[i]) } // Prints the expected |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment