Add SingleInlineArray utility.

This commit is contained in:
Andrew Trick
2024-01-05 18:02:40 -08:00
parent 87af731a0b
commit a756d38cf5

View File

@@ -114,6 +114,37 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren {
public static func ~=(pattern: StaticString, value: StringRef) -> Bool { value == pattern }
}
//===----------------------------------------------------------------------===//
// Single-Element Inline Array
//===----------------------------------------------------------------------===//
public struct SingleInlineArray<Element>: RandomAccessCollection {
private var singleElement: Element? = nil
private var multipleElements: [Element] = []
public init() {}
public var startIndex: Int { 0 }
public var endIndex: Int {
singleElement == nil ? 0 : multipleElements.count + 1
}
public subscript(_ index: Int) -> Element {
if index == 0 {
return singleElement!
}
return multipleElements[index - 1]
}
public mutating func push(_ element: Element) {
guard singleElement != nil else {
singleElement = element
return
}
multipleElements.append(element)
}
}
//===----------------------------------------------------------------------===//
// Bridging Utilities
//===----------------------------------------------------------------------===//