From f4dadc0071d42feb2ea456cbe301e2e2efab5938 Mon Sep 17 00:00:00 2001 From: overlookmotel Date: Sun, 7 Jan 2024 13:17:07 +0000 Subject: [PATCH] Align InlineBuffer same as Repr Fixes #353. --- compact_str/src/repr/heap.rs | 1 + compact_str/src/repr/inline.rs | 17 ++++++++++++----- compact_str/src/repr/static_str.rs | 1 + 3 files changed, 14 insertions(+), 5 deletions(-) diff --git a/compact_str/src/repr/heap.rs b/compact_str/src/repr/heap.rs index aa0f1bf96..e9feb8e9f 100644 --- a/compact_str/src/repr/heap.rs +++ b/compact_str/src/repr/heap.rs @@ -39,6 +39,7 @@ pub struct HeapBuffer { pub cap: Capacity, } static_assertions::assert_eq_size!(HeapBuffer, Repr); +static_assertions::assert_eq_align!(HeapBuffer, Repr); impl HeapBuffer { /// Create a [`HeapBuffer`] with the provided text diff --git a/compact_str/src/repr/inline.rs b/compact_str/src/repr/inline.rs index df4aa7f46..e539dfb95 100644 --- a/compact_str/src/repr/inline.rs +++ b/compact_str/src/repr/inline.rs @@ -7,9 +7,16 @@ use super::{ }; /// A buffer stored on the stack whose size is equal to the stack size of `String` -#[repr(transparent)] +#[cfg(target_pointer_width = "64")] +#[repr(C, align(8))] pub struct InlineBuffer(pub [u8; MAX_SIZE]); + +#[cfg(target_pointer_width = "32")] +#[repr(C, align(4))] +pub struct InlineBuffer(pub [u8; MAX_SIZE]); + static_assertions::assert_eq_size!(InlineBuffer, Repr); +static_assertions::assert_eq_align!(InlineBuffer, Repr); impl InlineBuffer { /// Construct a new [`InlineString`]. A string that lives in a small buffer on the stack @@ -21,10 +28,10 @@ impl InlineBuffer { debug_assert!(text.len() <= MAX_SIZE); let len = text.len(); - let mut buffer = [0u8; MAX_SIZE]; + let mut buffer = InlineBuffer([0u8; MAX_SIZE]); // set the length in the last byte - buffer[MAX_SIZE - 1] = len as u8 | LENGTH_MASK; + buffer.0[MAX_SIZE - 1] = len as u8 | LENGTH_MASK; // copy the string into our buffer // @@ -37,9 +44,9 @@ impl InlineBuffer { // * dst (`buffer`) is valid for `len` bytes because we assert src is less than MAX_SIZE // * src and dst don't overlap because we created dst // - ptr::copy_nonoverlapping(text.as_ptr(), buffer.as_mut_ptr(), len); + ptr::copy_nonoverlapping(text.as_ptr(), buffer.0.as_mut_ptr(), len); - InlineBuffer(buffer) + buffer } #[inline] diff --git a/compact_str/src/repr/static_str.rs b/compact_str/src/repr/static_str.rs index 404cfd9be..2e453c45e 100644 --- a/compact_str/src/repr/static_str.rs +++ b/compact_str/src/repr/static_str.rs @@ -24,6 +24,7 @@ pub struct StaticStr { discriminant: [u8; DISCRIMINANT_SIZE], } static_assertions::assert_eq_size!(StaticStr, Repr); +static_assertions::assert_eq_align!(StaticStr, Repr); static_assertions::assert_eq_size!(&'static str, (*const u8, usize)); impl StaticStr {