Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// A slitghtly silly example of a fixed array prototype
enum SmallArrayEnum<E>: RandomAccessCollection, MutableCollection {
init() {
self = .count0
}
var startIndex: Int { 0 }
var endIndex: Int {
switch self {
case .count0:
return 0
case .count1(_):
return 1
case .count2(_, _):
return 2
case .count3(_, _, _):
return 3
}
}
func invalidIndex() -> Never {
fatalError("invalid index")
}
subscript(position: Int) -> E {
get {
switch position {
case 0:
switch self {
case .count0: invalidIndex()
case .count1(let e): return e
case .count2(let e, _): return e
case .count3(let e, _, _): return e
}
case 1:
switch self {
case .count0, .count1: invalidIndex()
case .count2(_, let e): return e
case .count3(_, let e, _): return e
}
case 2:
switch self {
case .count0, .count1, .count2: invalidIndex()
case .count3(_, _, let e): return e
}
default: invalidIndex()
}
}
set {
switch self {
case .count0:
invalidIndex()
case .count1(_):
guard position == 0 else { invalidIndex() }
self = .count1(newValue)
case let .count2(e0, e1):
switch position {
case 0: self = .count2(newValue, e1)
case 1: self = .count2(e0, newValue)
default: invalidIndex()
}
case let .count3(e0, e1, e2):
switch position {
case 0: self = .count3(newValue, e1, e2)
case 1: self = .count3(e0, newValue, e2)
case 2: self = .count3(e0, e1, newValue)
default: invalidIndex()
}
}
}
}
case count0
case count1(E)
case count2(E, E)
case count3(E, E, E)
@discardableResult
mutating func append(_ element: E) -> Bool {
switch self {
case .count0:
self = .count1(element)
return true
case let .count1(e1):
self = .count2(e1, element)
return true
case let .count2(e1, e2):
self = .count3(e1, e2, element)
return true
case .count3(_, _, _):
return false
}
}
}
do {
var x = SmallArrayEnum<Int>()
x.count
x.append(1)
x[0]
x.append(2)
x[1]
x[0] = 10
x[0]
x.append(3)
x.reduce(0, +)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment