Skip to content

Commit 4ec403c

Browse files
committed
gh-156379: Avoid materializing large sequence ranges in mailbox.MH.get_sequences
Intersect declared ranges directly with all_keys instead of enumerating the entire interval into a set.
1 parent fe3a26f commit 4ec403c

3 files changed

Lines changed: 17 additions & 6 deletions

File tree

Lib/mailbox.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1236,14 +1236,15 @@ def get_sequences(self):
12361236
keys = set()
12371237
for spec in contents.split():
12381238
if spec.isdigit():
1239-
keys.add(int(spec))
1239+
key = int(spec)
1240+
if key in all_keys:
1241+
keys.add(key)
12401242
else:
12411243
start, stop = (int(x) for x in spec.split('-'))
1242-
keys.update(range(start, stop + 1))
1243-
results[name] = [key for key in sorted(keys) \
1244-
if key in all_keys]
1245-
if len(results[name]) == 0:
1246-
del results[name]
1244+
if start <= stop:
1245+
keys.update(k for k in all_keys if start <= k <= stop)
1246+
if keys:
1247+
results[name] = sorted(keys)
12471248
except ValueError:
12481249
raise FormatError('Invalid sequence specification: %s' %
12491250
line.rstrip())

Lib/test/test_mailbox.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1408,6 +1408,15 @@ def test_sequences(self):
14081408
self._box.set_sequences({'foo':[key0]})
14091409
self.assertEqual(self._box.get_sequences(), {'foo':[key0]})
14101410

1411+
def test_large_sequence_range(self):
1412+
# gh-156379: Verify large sequence ranges do not materialize large intervals
1413+
msg0 = mailbox.MHMessage(self._template % 0)
1414+
key0 = self._box.add(msg0)
1415+
seq_path = os.path.join(self._path, '.mh_sequences')
1416+
with open(seq_path, 'w', encoding='ASCII') as f:
1417+
f.write(f'unseen: 1-10000000\nempty: 50-100\n')
1418+
self.assertEqual(self._box.get_sequences(), {'unseen': [key0]})
1419+
14111420
def test_no_dot_mh_sequences_file(self):
14121421
path = os.path.join(self._path, 'foo.bar')
14131422
os.mkdir(path)
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Avoid materializing large sequence ranges in :meth:`mailbox.MH.get_sequences`.

0 commit comments

Comments
 (0)