Skip to content

Commit

Permalink
Derive Eq/PartialEq instead of manually implementing it
Browse files Browse the repository at this point in the history
  • Loading branch information
scottmcm committed Sep 22, 2022
1 parent e2d7cdc commit c158b7b
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions library/core/src/ptr/alignment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,34 @@ use crate::{cmp, fmt, hash, mem, num};
/// Note that particularly large alignments, while representable in this type,
/// are likely not to be supported by actual allocators and linkers.
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
#[derive(Copy, Clone)]
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(transparent)]
pub struct Alignment(AlignmentEnum);

// Alignment is `repr(usize)`, but via extra steps.
const _: () = assert!(mem::size_of::<Alignment>() == mem::size_of::<usize>());
const _: () = assert!(mem::align_of::<Alignment>() == mem::align_of::<usize>());

fn _alignment_can_be_structurally_matched(a: Alignment) -> bool {
matches!(a, Alignment::MIN)
}

impl Alignment {
/// The smallest possible alignment, 1.
///
/// All addresses are always aligned at least this much.
///
/// # Examples
///
/// ```
/// #![feature(ptr_alignment_type)]
/// use std::ptr::Alignment;
///
/// assert_eq!(Alignment::MIN.as_usize(), 1);
/// ```
#[unstable(feature = "ptr_alignment_type", issue = "102070")]
pub const MIN: Self = Self(AlignmentEnum::_Align1Shl0);

/// Returns the alignment for a type.
///
/// This provides the same numerical value as [`mem::align_of`],
Expand Down Expand Up @@ -127,17 +146,6 @@ impl TryFrom<usize> for Alignment {
}
}

#[unstable(feature = "ptr_alignment_type", issue = "102070")]
impl cmp::Eq for Alignment {}

#[unstable(feature = "ptr_alignment_type", issue = "102070")]
impl cmp::PartialEq for Alignment {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_nonzero() == other.as_nonzero()
}
}

#[unstable(feature = "ptr_alignment_type", issue = "102070")]
impl cmp::Ord for Alignment {
#[inline]
Expand Down Expand Up @@ -169,7 +177,7 @@ type AlignmentEnum = AlignmentEnum32;
#[cfg(target_pointer_width = "64")]
type AlignmentEnum = AlignmentEnum64;

#[derive(Copy, Clone)]
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(u16)]
enum AlignmentEnum16 {
_Align1Shl0 = 1 << 0,
Expand All @@ -190,7 +198,7 @@ enum AlignmentEnum16 {
_Align1Shl15 = 1 << 15,
}

#[derive(Copy, Clone)]
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(u32)]
enum AlignmentEnum32 {
_Align1Shl0 = 1 << 0,
Expand Down Expand Up @@ -227,7 +235,7 @@ enum AlignmentEnum32 {
_Align1Shl31 = 1 << 31,
}

#[derive(Copy, Clone)]
#[derive(Copy, Clone, Eq, PartialEq)]
#[repr(u64)]
enum AlignmentEnum64 {
_Align1Shl0 = 1 << 0,
Expand Down

0 comments on commit c158b7b

Please sign in to comment.