Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion hashset/hashset.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ pub fn[K] HashSet::new(capacity? : Int = default_init_capacity) -> HashSet[K] {
#alias(of, deprecated="Use from_array instead")
#as_free_fn(of, deprecated="Use from_array instead")
pub fn[K : Hash + Eq] HashSet::from_array(arr : ArrayView[K]) -> HashSet[K] {
let m = new()
let length = arr.length()
let mut capacity = length.next_power_of_two()
if length >= calc_grow_threshold(capacity) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Off-by-one: >= should be > in capacity pre-allocation check, causing unnecessary doubling

The condition length >= calc_grow_threshold(capacity) at line 42 uses >= instead of >. Since add_with_hash (hashset.mbt:80) checks self.size >= self.grow_at before inserting, the set can hold exactly grow_at elements without triggering growth. Therefore, length == calc_grow_threshold(capacity) does not require a capacity increase. The equivalent Set::from_array in set/linked_hash_set.mbt:80 correctly uses >. For example, with length=6 and capacity=8, calc_grow_threshold(8) = 6, and 6 elements fit in capacity 8 without triggering growth—but the >= condition unnecessarily doubles capacity to 16.

Suggested change
if length >= calc_grow_threshold(capacity) {
if length > calc_grow_threshold(capacity) {
Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

capacity = capacity * 2
}
let m = new(capacity~)
arr.each(e => m.add(e))
m
}
Expand Down
Loading