about summary refs log tree commit diff
path: root/library/core/src/alloc
diff options
context:
space:
mode:
authorDylan DPC <99973273+Dylan-DPC@users.noreply.github.com>2022-04-09 18:26:25 +0200
committerGitHub <noreply@github.com>2022-04-09 18:26:25 +0200
commite4b4bf1535ab3539c4573c8d960214c6e49eb138 (patch)
tree4d1f4e3804268b1973d078805dc4f6537473cc99 /library/core/src/alloc
parent1ced0b61a43d67ef209fc2fa8c4da783daa2471e (diff)
parentfe0c08a4f24ff7e6fb03b61656436bfa5ff29ac7 (diff)
downloadrust-e4b4bf1535ab3539c4573c8d960214c6e49eb138.tar.gz
rust-e4b4bf1535ab3539c4573c8d960214c6e49eb138.zip
Rollup merge of #95361 - scottmcm:valid-align, r=Mark-Simulacrum
Make non-power-of-two alignments a validity error in `Layout`

Inspired by the zulip conversation about how `Layout` should better enforce `size <= isize::MAX as usize`, this uses an N-variant enum on N-bit platforms to require at the validity level that the existing invariant of "must be a power of two" is upheld.

This was MIRI can catch it, and means there's a more-specific type for `Layout` to store than just `NonZeroUsize`.

It's left as `pub(crate)` here; a future PR could consider giving it a tracking issue for non-internal usage.
Diffstat (limited to 'library/core/src/alloc')
-rw-r--r--library/core/src/alloc/layout.rs11
1 files changed, 5 insertions, 6 deletions
diff --git a/library/core/src/alloc/layout.rs b/library/core/src/alloc/layout.rs
index db6898c1308..612e366cedf 100644
--- a/library/core/src/alloc/layout.rs
+++ b/library/core/src/alloc/layout.rs
@@ -1,7 +1,6 @@
 use crate::cmp;
 use crate::fmt;
-use crate::mem;
-use crate::num::NonZeroUsize;
+use crate::mem::{self, ValidAlign};
 use crate::ptr::NonNull;
 
 // While this function is used in one place and its implementation
@@ -40,7 +39,7 @@ pub struct Layout {
     //
     // (However, we do not analogously require `align >= sizeof(void*)`,
     //  even though that is *also* a requirement of `posix_memalign`.)
-    align_: NonZeroUsize,
+    align_: ValidAlign,
 }
 
 impl Layout {
@@ -97,8 +96,8 @@ impl Layout {
     #[must_use]
     #[inline]
     pub const unsafe fn from_size_align_unchecked(size: usize, align: usize) -> Self {
-        // SAFETY: the caller must ensure that `align` is greater than zero.
-        Layout { size_: size, align_: unsafe { NonZeroUsize::new_unchecked(align) } }
+        // SAFETY: the caller must ensure that `align` is a power of two.
+        Layout { size_: size, align_: unsafe { ValidAlign::new_unchecked(align) } }
     }
 
     /// The minimum size in bytes for a memory block of this layout.
@@ -117,7 +116,7 @@ impl Layout {
                   without modifying the layout"]
     #[inline]
     pub const fn align(&self) -> usize {
-        self.align_.get()
+        self.align_.as_nonzero().get()
     }
 
     /// Constructs a `Layout` suitable for holding a value of type `T`.