Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: Remove panics from some Layout methods #49884

Merged
merged 1 commit into from
Apr 15, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions src/libcore/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,15 +145,26 @@ impl Layout {
/// Constructs a `Layout` suitable for holding a value of type `T`.
pub fn new<T>() -> Self {
let (size, align) = size_align::<T>();
Layout::from_size_align(size, align).unwrap()
// Note that the align is guaranteed by rustc to be a power of two and
// the size+align combo is guaranteed to fit in our address space. As a
// result use the unchecked constructor here to avoid inserting code
// that panics if it isn't optimized well enough.
debug_assert!(Layout::from_size_align(size, align).is_ok());
unsafe {
Layout::from_size_align_unchecked(size, align)
}
}

/// Produces layout describing a record that could be used to
/// allocate backing structure for `T` (which could be a trait
/// or other unsized type like a slice).
pub fn for_value<T: ?Sized>(t: &T) -> Self {
let (size, align) = (mem::size_of_val(t), mem::align_of_val(t));
Layout::from_size_align(size, align).unwrap()
// See rationale in `new` for why this us using an unsafe variant below
debug_assert!(Layout::from_size_align(size, align).is_ok());
unsafe {
Layout::from_size_align_unchecked(size, align)
}
}

/// Creates a layout describing the record that can hold a value
Expand Down Expand Up @@ -234,12 +245,7 @@ impl Layout {
.ok_or(LayoutErr { private: () })?;
let alloc_size = padded_size.checked_mul(n)
.ok_or(LayoutErr { private: () })?;

// We can assume that `self.align` is a power-of-two.
// Furthermore, `alloc_size` has already been rounded up
// to a multiple of `self.align`; therefore, the call to
// `Layout::from_size_align` below should never panic.
Ok((Layout::from_size_align(alloc_size, self.align).unwrap(), padded_size))
Ok((Layout::from_size_align(alloc_size, self.align)?, padded_size))
}

/// Creates a layout describing the record for `self` followed by
Expand Down