Skip to content

Instantly share code, notes, and snippets.

@jepers
Created December 1, 2015 21:59
Show Gist options
  • Save jepers/39b47f269911d5e1cc81 to your computer and use it in GitHub Desktop.
Save jepers/39b47f269911d5e1cc81 to your computer and use it in GitHub Desktop.
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