Skip to content

Commit 204d264

Browse files
committed
gh-137928: Move size validation helper to module level in multiprocessing.heap
1 parent 8c3baf0 commit 204d264

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

Lib/multiprocessing/heap.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,12 @@
2020

2121
__all__ = ['BufferWrapper']
2222

23+
#
24+
# Module constants
25+
#
26+
27+
_MAXSIZE = sys.maxsize
28+
2329
#
2430
# Inheritable class which wraps an mmap, and from which blocks can be allocated
2531
#
@@ -108,6 +114,17 @@ def rebuild_arena(size, dupfd):
108114

109115
reduction.register(Arena, reduce_arena)
110116

117+
#
118+
# Validation helpers
119+
#
120+
121+
def _validate_size(size):
122+
"""Validate requested size; raise ValueError if < 0, OverflowError if >= _MAXSIZE."""
123+
if size < 0:
124+
raise ValueError("Size {0:n} out of range".format(size))
125+
if _MAXSIZE <= size:
126+
raise OverflowError("Size {0:n} too large".format(size))
127+
111128
#
112129
# Class allowing allocation of chunks of memory from arenas
113130
#
@@ -155,15 +172,6 @@ def _roundup(n, alignment):
155172
mask = alignment - 1
156173
return (n + mask) & ~mask
157174

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-
167175
def _new_arena(self, size):
168176
# Create a new arena with at least the given *size*
169177
length = self._roundup(max(self._size, size), mmap.PAGESIZE)
@@ -304,7 +312,7 @@ def free(self, block):
304312

305313
def malloc(self, size):
306314
# return a block of right size (possibly rounded up)
307-
Heap._validate_size(size)
315+
_validate_size(size)
308316
if os.getpid() != self._lastpid:
309317
self.__init__() # reinitialize after fork
310318
with self._lock:
@@ -330,7 +338,7 @@ class BufferWrapper(object):
330338
_heap = Heap()
331339

332340
def __init__(self, size):
333-
Heap._validate_size(size)
341+
_validate_size(size)
334342
block = BufferWrapper._heap.malloc(size)
335343
self._state = (block, size)
336344
util.Finalize(self, BufferWrapper._heap.free, args=(block,))

0 commit comments

Comments
 (0)