Skip to content

Commit 8c3baf0

Browse files
committed
gh-137928: Centralize size validation in multiprocessing.heap
1 parent 3706ef6 commit 8c3baf0

File tree

1 file changed

+11
-8
lines changed

1 file changed

+11
-8
lines changed

Lib/multiprocessing/heap.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,15 @@ def _roundup(n, alignment):
155155
mask = alignment - 1
156156
return (n + mask) & ~mask
157157

158+
@staticmethod
159+
# Bind sys.maxsize once at function definition time to avoid global lookups.
160+
def _validate_size(size, _maxsize=sys.maxsize):
161+
"""Validate requested size; raise ValueError if < 0, OverflowError if >= _maxsize."""
162+
if size < 0:
163+
raise ValueError("Size {0:n} out of range".format(size))
164+
if _maxsize <= size:
165+
raise OverflowError("Size {0:n} too large".format(size))
166+
158167
def _new_arena(self, size):
159168
# Create a new arena with at least the given *size*
160169
length = self._roundup(max(self._size, size), mmap.PAGESIZE)
@@ -295,10 +304,7 @@ def free(self, block):
295304

296305
def malloc(self, size):
297306
# return a block of right size (possibly rounded up)
298-
if size < 0:
299-
raise ValueError("Size {0:n} out of range".format(size))
300-
if sys.maxsize <= size:
301-
raise OverflowError("Size {0:n} too large".format(size))
307+
Heap._validate_size(size)
302308
if os.getpid() != self._lastpid:
303309
self.__init__() # reinitialize after fork
304310
with self._lock:
@@ -324,10 +330,7 @@ class BufferWrapper(object):
324330
_heap = Heap()
325331

326332
def __init__(self, size):
327-
if size < 0:
328-
raise ValueError("Size {0:n} out of range".format(size))
329-
if sys.maxsize <= size:
330-
raise OverflowError("Size {0:n} too large".format(size))
333+
Heap._validate_size(size)
331334
block = BufferWrapper._heap.malloc(size)
332335
self._state = (block, size)
333336
util.Finalize(self, BufferWrapper._heap.free, args=(block,))

0 commit comments

Comments
 (0)