Skip to content

Commit d2f09cf

Browse files
committed
♻️ Avoid unnecessary allocation in SequenceSet[]
This updates the behavior of `SequenceSet[]` so that a frozen result from `input.to_sequence_set` is returned directly, not duplicated. It is also updated to delegate to `SequenceSet.try_convert`.
1 parent 2bc753f commit d2f09cf

File tree

2 files changed

+13
-5
lines changed

2 files changed

+13
-5
lines changed

lib/net/imap/sequence_set.rb

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -390,11 +390,8 @@ class << self
390390
# Related: ::new, ::try_convert
391391
def [](first, *rest)
392392
if rest.empty?
393-
if first.is_a?(SequenceSet) && first.frozen? && first.valid?
394-
first
395-
else
396-
new(first).validate.freeze
397-
end
393+
set = try_convert(first)&.validate
394+
set&.frozen? ? set : (set&.dup || new(first).validate).freeze
398395
else
399396
new(first).merge(*rest).validate.freeze
400397
end

test/net/imap/test_sequence_set.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,17 @@ def compare_to_reference_set(nums, set, seqset)
237237
test ".[frozen SequenceSet] returns that SequenceSet" do
238238
frozen_seqset = SequenceSet[123..456]
239239
assert_same frozen_seqset, SequenceSet[frozen_seqset]
240+
241+
coercible = Object.new
242+
frozen_seqset = SequenceSet[192, 168, 1, 255]
243+
coercible.define_singleton_method(:to_sequence_set) { frozen_seqset }
244+
assert_same frozen_seqset, SequenceSet[coercible]
245+
246+
coercible = Object.new
247+
mutable_seqset = SequenceSet.new([192, 168, 1, 255])
248+
coercible.define_singleton_method(:to_sequence_set) { mutable_seqset }
249+
assert_equal mutable_seqset, SequenceSet[coercible]
250+
refute_same mutable_seqset, SequenceSet[coercible]
240251
end
241252

242253
test ".new, input may be empty" do

0 commit comments

Comments
 (0)