From 6b90391c227964c90303e591b0dc2b92e33d90ac Mon Sep 17 00:00:00 2001 From: Artem Kryvokrysenko Date: Sun, 16 Mar 2025 07:37:47 +0000 Subject: [PATCH] Add Alignment::new constructor function Currently the only way to construct Aligned value is using `aligned::Aligned` function which returns instance of `Aligned` struct. This does not work well with type aliases. For example, consider this type alias: ``` /// Aligns value at cache line boundary (assuming 64 byte cache line size) type CacheLineAligned = Aligned; ``` User still has to use `aligned::Aligned` function to create value which breaks abstraction provided by type alias: ``` let cache_aligned_value: CacheLineAligned = aligned::Aligned(42); ``` In this commit I am implementing a conventional `new` constructor for `struct Aligned` which works with type aliases: ``` let cache_aligned_value = CacheLineAligned::new(42_u32); ``` --- src/lib.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 0caeabc..6223feb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -155,6 +155,20 @@ where } } +impl Aligned +where + A: Alignment, +{ + /// Changes the alignment of value to be at least A bytes + pub const fn new(value: T) -> Self { + Aligned { + _alignment: [], + value, + } + } +} + + impl Aligned where A: Alignment, @@ -525,6 +539,16 @@ fn sanity() { let _: &[u8] = y; } +#[test] +fn test_type_alias_new() { + type CacheLineAligned = Aligned; + + let aligned: Aligned = Aligned([0u8; 3]); + let aligned_new = CacheLineAligned::new([0u8; 3]); + + assert_eq!(aligned, aligned_new); +} + #[test] fn test_range_to() { let a: &Aligned = &Aligned::([0, 1, 2, 3]);