Hi!
As a fun experiment, I wanted to see if I could make a "SmallArray" type that would have a fixed maximum size and not require a heap allocation. I wanted to make this type conform to RandomAccessCollection and also avoid having a bunch of branch instructions in my subscript operator.
This is what I tried:
struct SmallArray<Element>: RandomAccessCollection {
var startIndex: Int { 0 }
var endIndex: Int { _count }
subscript(position: Int) -> Element {
mutating get {
precondition(indices.contains(position), "invalid index")
withUnsafePointer(to: &_e0) { buffer in
(buffer + position).pointee
}
}
}
internal var _count: Int
internal var _e0, _e1, _e2, _e3, _e4, _e5: Element
}
I have to make the get
accessor mutable to get at the _e0 pointer, but this breaks conformance for RandomAccessCollection. Hmm... Any tricks?