Methods that fully consume a cursor prefer forEach to next

This allows custom forEach implementations to wrap the full consumption of a cursor
This commit is contained in:
Gwendal Roué committed 2022-01-08 13:50:14 +01:00
1 parent 823af1944e
commit fc0e1bede1
1 file changed
+8 -16
+8 -16
View File
@@ -21,9 +21,7 @@ extension RangeReplaceableCollection {
/// - parameter cursor: The cursor whose elements feed the collection.
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
append(element)
}
try cursor.forEach { append($0) }
}
/// Creates a collection containing the elements of a cursor.
@@ -38,9 +36,7 @@ extension RangeReplaceableCollection {
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
self.init()
reserveCapacity(minimumCapacity)
while let element = try cursor.next() {
append(element)
}
try cursor.forEach { append($0) }
}
}
@@ -60,7 +56,7 @@ extension Dictionary {
throws where Value == [C.Element]
{
self.init()
while let value = try cursor.next() {
try cursor.forEach { value in
try self[keyForValue(value), default: []].append(value)
}
}
@@ -86,7 +82,7 @@ extension Dictionary {
throws where Value == [C.Element]
{
self.init(minimumCapacity: minimumCapacity)
while let value = try cursor.next() {
try cursor.forEach { value in
try self[keyForValue(value), default: []].append(value)
}
}
@@ -108,7 +104,7 @@ extension Dictionary {
throws where C.Element == (Key, Value)
{
self.init()
while let (key, value) = try keysAndValues.next() {
try keysAndValues.forEach { key, value in
if updateValue(value, forKey: key) != nil {
fatalError("Duplicate values for key: '\(String(describing: key))'")
}
@@ -137,7 +133,7 @@ extension Dictionary {
throws where C.Element == (Key, Value)
{
self.init(minimumCapacity: minimumCapacity)
while let (key, value) = try keysAndValues.next() {
try keysAndValues.forEach { key, value in
if updateValue(value, forKey: key) != nil {
fatalError("Duplicate values for key: '\(String(describing: key))'")
}
@@ -155,9 +151,7 @@ extension Set {
/// - parameter cursor: A cursor of values to gather into a set.
public init<C: Cursor>(_ cursor: C) throws where C.Element == Element {
self.init()
while let element = try cursor.next() {
insert(element)
}
try cursor.forEach { insert($0) }
}
/// Creates a set containing the elements of a cursor.
@@ -172,9 +166,7 @@ extension Set {
/// storage buffer.
public init<C: Cursor>(_ cursor: C, minimumCapacity: Int) throws where C.Element == Element {
self.init(minimumCapacity: minimumCapacity)
while let element = try cursor.next() {
insert(element)
}
try cursor.forEach { insert($0) }
}
}