Skip to content

Add Alignment::new constructor function #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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<T> = Aligned<A64, T>;
```

User still has to use `aligned::Aligned` function to create value which breaks
abstraction provided by type alias:

```
let cache_aligned_value: CacheLineAligned<u32> = 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);
```
  • Loading branch information
Artem Kryvokrysenko committed Mar 16, 2025
commit 6b90391c227964c90303e591b0dc2b92e33d90ac
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,20 @@ where
}
}

impl<A, T> Aligned<A, T>
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<A, T> Aligned<A, [T]>
where
A: Alignment,
Expand Down Expand Up @@ -525,6 +539,16 @@ fn sanity() {
let _: &[u8] = y;
}

#[test]
fn test_type_alias_new() {
type CacheLineAligned<T> = Aligned<A64, T>;

let aligned: Aligned<A64, _> = Aligned([0u8; 3]);
let aligned_new = CacheLineAligned::new([0u8; 3]);

assert_eq!(aligned, aligned_new);
}

#[test]
fn test_range_to() {
let a: &Aligned<A2, [u8]> = &Aligned::<A2, _>([0, 1, 2, 3]);
Expand Down