@@ -196,19 +196,55 @@ impl Heap {
196
196
self . size ( ) - self . used
197
197
}
198
198
199
- /// Extends the size of the heap by creating a new hole at the end
199
+ /// Extends the size of the heap by creating a new hole at the end.
200
+ ///
201
+ /// Panics when the heap extension fails. Use [`try_extend`] to handle potential errors.
200
202
///
201
203
/// # Safety
202
204
///
203
205
/// The amount of data given in `by` MUST exist directly after the original
204
206
/// range of data provided when constructing the [Heap]. The additional data
205
207
/// must have the same lifetime of the original range of data.
206
208
pub unsafe fn extend ( & mut self , by : usize ) {
207
- let top = self . top ( ) ;
208
- let layout = Layout :: from_size_align ( by, 1 ) . unwrap ( ) ;
209
- self . holes
210
- . deallocate ( NonNull :: new_unchecked ( top as * mut u8 ) , layout) ;
211
- self . holes . top = self . holes . top . add ( by) ;
209
+ self . holes . try_extend ( by) . expect ( "heap extension failed" ) ;
210
+ }
211
+
212
+ /// Tries to extend the size of the heap by creating a new hole at the end.
213
+ ///
214
+ /// # Safety
215
+ ///
216
+ /// The amount of data given in `by` MUST exist directly after the original
217
+ /// range of data provided when constructing the [Heap]. The additional data
218
+ /// must have the same lifetime of the original range of data.
219
+ pub unsafe fn try_extend ( & mut self , by : usize ) -> Result < ( ) , ExtendError > {
220
+ self . holes . try_extend ( by)
221
+ }
222
+ }
223
+
224
+ #[ derive( Debug , PartialEq , Eq , Clone , Copy ) ]
225
+ pub enum ExtendError {
226
+ /// The given extension size was not large enough to store the necessary metadata.
227
+ SizeTooSmall ,
228
+ /// The given extension size was must be a multiple of 16.
229
+ OddSize ,
230
+ /// The heap size must be a multiple of 16, otherwise extension is not possible.
231
+ OddHeapSize ,
232
+ /// Extending an empty heap is not possible.
233
+ EmptyHeap ,
234
+ }
235
+
236
+ impl core:: fmt:: Display for ExtendError {
237
+ fn fmt ( & self , f : & mut core:: fmt:: Formatter < ' _ > ) -> core:: fmt:: Result {
238
+ f. write_str ( match self {
239
+ ExtendError :: SizeTooSmall => {
240
+ "heap extension size was not large enough to store the necessary metadata"
241
+ }
242
+ ExtendError :: OddSize => "heap extension size is not a multiple of 16" ,
243
+ ExtendError :: OddHeapSize => {
244
+ "heap extension not possible because heap size is not a multiple of 16"
245
+ }
246
+ ExtendError :: EmptyHeap => "tried to extend an emtpy heap" ,
247
+ } )
212
248
}
213
249
}
214
250
0 commit comments