Visitar URL original
Fix assertion for backing storage with small alignment · bodil/sized-chunks@b3ebeb0 · GitHub
Skip to content
This repository was archived by the owner on May 3, 2026. It is now read-only.

Commit b3ebeb0

Browse files
committed
Fix assertion for backing storage with small alignment
1 parent aa40821 commit b3ebeb0

1 file changed

Lines changed: 16 additions & 8 deletions

File tree

‎src/inline_array/mod.rs‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -76,13 +76,13 @@ pub use self::iter::{Drain, Iter};
7676
pub struct InlineArray<A, T> {
7777
// Alignment tricks
7878
//
79-
// We need both the usize header and data to be properly aligned in memory. We do a few tricks
79+
// We need both the `_header_align` and `data` to be properly aligned in memory. We do a few tricks
8080
// to handle that.
8181
//
8282
// * An alignment is always power of 2. Therefore, with a pair of alignments, one is always
8383
// a multiple of the other (one way or the other).
8484
// * A struct is aligned to at least the max alignment of each of its fields.
85-
// * A repr(C) struct follows the order of fields and pushes each as close to the previous one
85+
// * A `repr(C)` struct follows the order of fields and pushes each as close to the previous one
8686
// as allowed by alignment.
8787
//
8888
// By placing two "fake" fields that have 0 size, but an alignment first, we make sure that all
@@ -267,17 +267,14 @@ impl<A, T> InlineArray<A, T> {
267267
self_.data.as_ptr() as usize,
268268
"Padding at the start of struct",
269269
);
270-
assert_eq!(mem::size_of::<Self>(), mem::size_of::<T>());
271270
assert_eq!(
272271
self_.data.as_ptr() as usize % mem::align_of::<usize>(),
273272
0,
274273
"Unaligned header"
275274
);
276-
assert_eq!(
277-
self_.data.as_ptr() as usize % mem::align_of::<A>(),
278-
0,
279-
"Unaligned elements"
280-
);
275+
assert!(mem::size_of::<Self>() == mem::size_of::<T>() || mem::align_of::<T>() < mem::align_of::<Self>());
276+
assert_eq!(0, unsafe { self_.data() } as usize % mem::align_of::<A>());
277+
assert_eq!(0, unsafe { self_.data_mut() } as usize % mem::align_of::<A>());
281278
assert!(Self::ELEMENT_SKIP == 0 || Self::HEADER_SKIP == 0);
282279
unsafe { ptr::write(self_.len_mut(), 0usize) };
283280
self_
@@ -638,6 +635,17 @@ mod test {
638635
assert_eq!(chunk[0], "Hello");
639636
}
640637

638+
#[test]
639+
fn float_align() {
640+
let mut chunk: InlineArray<f64, [u8; 16]> = InlineArray::new();
641+
chunk.push(1234.);
642+
assert_eq!(chunk[0], 1234.);
643+
644+
let mut chunk: InlineArray<f64, [u8; 17]> = InlineArray::new();
645+
chunk.push(1234.);
646+
assert_eq!(chunk[0], 1234.);
647+
}
648+
641649
#[test]
642650
fn recursive_types_compile() {
643651
#[allow(dead_code)]

0 commit comments

Comments
 (0)