iceoryx2_bb_elementary/
alignment.rs

1// Copyright (c) 2024 Contributors to the Eclipse Foundation
2//
3// See the NOTICE file(s) distributed with this work for additional
4// information regarding copyright ownership.
5//
6// This program and the accompanying materials are made available under the
7// terms of the Apache Software License 2.0 which is available at
8// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
9// which is available at https://opensource.org/licenses/MIT.
10//
11// SPDX-License-Identifier: Apache-2.0 OR MIT
12
13//! Represents the alignment memory can have. Ensures that the content is always
14//! a power of 2 and not zero.
15
16/// Contains the alignment memory can have.
17///
18/// # Example
19///
20/// ```
21/// use iceoryx2_bb_elementary::alignment::Alignment;
22///
23/// let my_alignment = Alignment::new(32).unwrap();
24///
25/// // zero is not a valid alignment
26/// let broken_alignment = Alignment::new(0);
27/// assert_eq!(broken_alignment, None);
28///
29/// // alignment must be a power of 2
30/// let broken_alignment = Alignment::new(89);
31/// assert_eq!(broken_alignment, None);
32/// ```
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
34pub struct Alignment(usize);
35
36impl Alignment {
37    pub const ALIGN_1: Alignment = Alignment(1);
38    pub const ALIGN_2: Alignment = Alignment(2);
39    pub const ALIGN_4: Alignment = Alignment(4);
40    pub const ALIGN_8: Alignment = Alignment(8);
41    pub const ALIGN_16: Alignment = Alignment(16);
42    pub const ALIGN_32: Alignment = Alignment(32);
43    pub const ALIGN_64: Alignment = Alignment(64);
44    pub const ALIGN_128: Alignment = Alignment(128);
45    pub const ALIGN_256: Alignment = Alignment(256);
46    pub const ALIGN_512: Alignment = Alignment(512);
47    pub const ALIGN_1024: Alignment = Alignment(1024);
48    pub const ALIGN_2048: Alignment = Alignment(2048);
49    pub const ALIGN_4096: Alignment = Alignment(4096);
50
51    /// Creates a new [`Alignment`]. If the value is zero or not a power of 2
52    /// it returns [`None`].
53    pub fn new(value: usize) -> Option<Self> {
54        (value.is_power_of_two()).then(|| unsafe { Self::new_unchecked(value) })
55    }
56
57    /// Creates a new [`Alignment`].
58    ///
59    /// # Safety
60    ///
61    ///  * The value must not be zero
62    ///  * The value must be a power of 2
63    ///
64    pub const unsafe fn new_unchecked(value: usize) -> Self {
65        Self(value)
66    }
67
68    /// Returns the value of the [`Alignment`]
69    pub const fn value(&self) -> usize {
70        self.0
71    }
72}