Skip to content

Commit a756d38

Browse files
committed
Add SingleInlineArray utility.
1 parent 87af731 commit a756d38

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

SwiftCompilerSources/Sources/Basic/Utils.swift

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,37 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren {
114114
public static func ~=(pattern: StaticString, value: StringRef) -> Bool { value == pattern }
115115
}
116116

117+
//===----------------------------------------------------------------------===//
118+
// Single-Element Inline Array
119+
//===----------------------------------------------------------------------===//
120+
121+
public struct SingleInlineArray<Element>: RandomAccessCollection {
122+
private var singleElement: Element? = nil
123+
private var multipleElements: [Element] = []
124+
125+
public init() {}
126+
127+
public var startIndex: Int { 0 }
128+
public var endIndex: Int {
129+
singleElement == nil ? 0 : multipleElements.count + 1
130+
}
131+
132+
public subscript(_ index: Int) -> Element {
133+
if index == 0 {
134+
return singleElement!
135+
}
136+
return multipleElements[index - 1]
137+
}
138+
139+
public mutating func push(_ element: Element) {
140+
guard singleElement != nil else {
141+
singleElement = element
142+
return
143+
}
144+
multipleElements.append(element)
145+
}
146+
}
147+
117148
//===----------------------------------------------------------------------===//
118149
// Bridging Utilities
119150
//===----------------------------------------------------------------------===//

0 commit comments

Comments
 (0)