Skip to content

Commit 3dcaf54

Browse files
committed
properly handle isize::MAX overflow
1 parent 35ed253 commit 3dcaf54

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

src/lib.rs

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -331,22 +331,26 @@ extern "C" {
331331
static EMPTY_HEADER: Header;
332332
}
333333

334-
// TODO: overflow checks everywhere
335-
336334
// Utils for computing layouts of allocations
337335

338336
fn alloc_size<T>(cap: usize) -> usize {
339337
// Compute "real" header size with pointer math
340-
let header_size = mem::size_of::<Header>();
341-
let elem_size = mem::size_of::<T>();
342-
let padding = padding::<T>();
338+
//
339+
// We turn everything into isizes here so that we can catch isize::MAX overflow,
340+
// we never want to allow allocations larger than that!
341+
let cap = cap as isize;
342+
let header_size = mem::size_of::<Header>() as isize;
343+
let elem_size = mem::size_of::<T>() as isize;
344+
let padding = padding::<T>() as isize;
343345

344-
// TODO: care about isize::MAX overflow?
345346
let data_size = elem_size.checked_mul(cap).expect("capacity overflow");
346347

347-
data_size
348+
let final_size = data_size
348349
.checked_add(header_size + padding)
349-
.expect("capacity overflow")
350+
.expect("capacity overflow");
351+
352+
// Ok now we can turn it back into a usize (don't need to worry about negatives)
353+
final_size as usize
350354
}
351355

352356
fn padding<T>() -> usize {
@@ -501,7 +505,7 @@ impl<T> ThinVec<T> {
501505
/// // A vector of a zero-sized type will always over-allocate, since no
502506
/// // space is needed to store the actual elements.
503507
/// let vec_units = ThinVec::<()>::with_capacity(10);
504-
///
508+
///
505509
/// // Only true **without** the gecko-ffi feature!
506510
/// // assert_eq!(vec_units.capacity(), usize::MAX);
507511
/// ```

0 commit comments

Comments
 (0)