Skip to content

Commit

Permalink
Merge pull request #107 from lorentey/let’s-table-that
Browse files Browse the repository at this point in the history
[OrderedSet] Don't let the unchecked init create large sets with no hash table
  • Loading branch information
lorentey authored Sep 10, 2021
2 parents 95fa069 + f69104b commit 37e15ae
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
27 changes: 12 additions & 15 deletions Sources/OrderedCollections/OrderedSet/OrderedSet+Initializers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,6 @@
//===----------------------------------------------------------------------===//

extension OrderedSet {
@inlinable
internal init(_uncheckedUniqueElements elements: ContiguousArray<Element>) {
#if DEBUG
self.init(_uniqueElements: elements)
#else
guard elements.count > _HashTable.maximumUnhashedCount else {
self.init(_uniqueElements: elements, nil)
return
}
let table = _HashTable.create(uncheckedUniqueElements: elements)
self.init(_uniqueElements: elements, table)
#endif
}

/// Creates a set with the contents of the given sequence, which
/// must not include duplicate elements.
///
Expand All @@ -44,7 +30,18 @@ extension OrderedSet {
@inline(__always)
public init<S: Sequence>(uncheckedUniqueElements elements: S)
where S.Element == Element {
self.init(_uncheckedUniqueElements: ContiguousArray<Element>(elements))
let elements = ContiguousArray<Element>(elements)
#if DEBUG
let (table, firstDupe) = _HashTable.create(untilFirstDuplicateIn: elements)
precondition(firstDupe == elements.endIndex,
"Duplicate elements found in input")
#else
let table = _HashTable.create(uncheckedUniqueElements: elements)
#endif
self.init(
_uniqueElements: elements,
elements.count > _HashTable.maximumUnhashedCount ? table : nil)
_checkInvariants()
}
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/OrderedCollections/OrderedSet/OrderedSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ public struct OrderedSet<Element> where Element: Hashable
@inlinable
internal init(
_uniqueElements: ContiguousArray<Element>,
_ table: _HashTable? = nil
_ table: _HashTable?
) {
self.__storage = table?._storage
self._elements = _uniqueElements
Expand Down

0 comments on commit 37e15ae

Please sign in to comment.