Skip to content

Commit b7a021f

Browse files
committed
Update trim(while:) - rethrowing and nonescaping
This eliminates PredicateConsumer from the implementation so that the closure can throw.
1 parent caad657 commit b7a021f

File tree

1 file changed

+18
-12
lines changed
  • Sources/_StringProcessing/Algorithms/Algorithms

1 file changed

+18
-12
lines changed

Sources/_StringProcessing/Algorithms/Algorithms/Trim.swift

Lines changed: 18 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -102,31 +102,37 @@ extension RangeReplaceableCollection where Self: BidirectionalCollection {
102102
// MARK: Predicate algorithms
103103

104104
extension Collection {
105-
// TODO: Non-escaping and throwing
106-
func trimmingPrefix(
107-
while predicate: @escaping (Element) -> Bool
108-
) -> SubSequence {
109-
trimmingPrefix(ManyConsumer(base: PredicateConsumer(predicate: predicate)))
105+
fileprivate func endOfPrefix(while predicate: (Element) throws -> Bool) rethrows -> Index {
106+
try firstIndex(where: { try !predicate($0) }) ?? endIndex
107+
}
108+
109+
@available(SwiftStdlib 5.7, *)
110+
public func trimmingPrefix(
111+
while predicate: (Element) throws -> Bool
112+
) rethrows -> SubSequence {
113+
let end = try endOfPrefix(while: predicate)
114+
return self[end...]
110115
}
111116
}
112117

113118
extension Collection where SubSequence == Self {
114119
@available(SwiftStdlib 5.7, *)
115120
public mutating func trimPrefix(
116-
while predicate: @escaping (Element) -> Bool
117-
) {
118-
trimPrefix(ManyConsumer(
119-
base: PredicateConsumer<SubSequence>(predicate: predicate)))
121+
while predicate: (Element) throws -> Bool
122+
) throws {
123+
let end = try endOfPrefix(while: predicate)
124+
self = self[end...]
120125
}
121126
}
122127

123128
extension RangeReplaceableCollection {
124129
@_disfavoredOverload
125130
@available(SwiftStdlib 5.7, *)
126131
public mutating func trimPrefix(
127-
while predicate: @escaping (Element) -> Bool
128-
) {
129-
trimPrefix(ManyConsumer(base: PredicateConsumer(predicate: predicate)))
132+
while predicate: (Element) throws -> Bool
133+
) rethrows {
134+
let end = try endOfPrefix(while: predicate)
135+
removeSubrange(startIndex..<end)
130136
}
131137
}
132138

0 commit comments

Comments
 (0)