@@ -92,20 +92,28 @@ def allocate(self, size: PositiveInt, purpose: str) -> Allocation:
9292 f"{ self ._name } { self ._owner } " , purpose , size , available
9393 )
9494 fragments = []
95- remaining_size = size
96- for block in self ._blocks :
97- while remaining_size > 0 :
98- fragment = block .take_fragment (remaining_size )
99- if fragment is None :
100- # The current block is exhausted, move on to the next block, if any.
95+ try :
96+ remaining_size = size
97+ for block in self ._blocks :
98+ while remaining_size > 0 :
99+ fragment = block .allocate_fragment (remaining_size )
100+ if fragment is None :
101+ # The current block is exhausted, move on to the next block, if any.
102+ break
103+ fragments .append (fragment )
104+ remaining_size -= fragment .size
105+ if remaining_size == 0 :
106+ # We have allocated the full desired size; don't need to look at any more blocks.
101107 break
102- fragments .append (fragment )
103- remaining_size -= fragment .size
104- if remaining_size == 0 :
105- # We have allocated the full desired size; don't need to look at any more blocks.
106- break
107- assert remaining_size == 0 # We checked availability at the top of the method.
108- return Allocation (fragments )
108+ assert (
109+ remaining_size == 0
110+ ) # We checked availability at the top of the method.
111+ return Allocation (fragments )
112+ except Exception as exc :
113+ # Allocation failed halfway; give back any fragments that were taken.
114+ for fragment in fragments :
115+ fragment .give_back ()
116+ raise exc
109117
110118 def mark_allocation_used (self , allocation : Allocation ):
111119 """
0 commit comments