Skip to content

Commit

Permalink
Align InlineBuffer same as Repr
Browse files Browse the repository at this point in the history
Fixes #353.
  • Loading branch information
overlookmotel committed Jan 7, 2024
1 parent 302c595 commit f4dadc0
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 5 deletions.
1 change: 1 addition & 0 deletions compact_str/src/repr/heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 12 additions & 5 deletions compact_str/src/repr/inline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
//
Expand All @@ -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]
Expand Down
1 change: 1 addition & 0 deletions compact_str/src/repr/static_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down

0 comments on commit f4dadc0

Please sign in to comment.