cel_runtime/memory.rs
1//! Computes byte offsets for aligned storage.
2//!
3//! Use [`align_index`] with a power-of-two alignment and a representable
4//! padded index before addressing an aligned buffer.
5
6/// Returns the least aligned index not smaller than `index`.
7///
8/// - Precondition: `align` is a power of two and `index + align - 1` is representable.
9///
10/// # Examples
11/// ```
12/// assert_eq!(cel_runtime::memory::align_index(8, 9), 16);
13/// ```
14///
15#[must_use]
16pub const fn align_index(align: usize, index: usize) -> usize {
17 debug_assert!(align.is_power_of_two());
18 debug_assert!(index <= usize::MAX - (align - 1));
19 (index + align - 1) & !(align - 1)
20}
21
22#[cfg(test)]
23mod tests {
24 use super::*;
25
26 /// Rounds up unaligned indexes and preserves aligned indexes.
27 #[test]
28 fn test_align_index() {
29 assert_eq!(align_index(16, 0), 0);
30 assert_eq!(align_index(16, 1), 16);
31 assert_eq!(align_index(16, 15), 16);
32 assert_eq!(align_index(16, 16), 16);
33 assert_eq!(align_index(16, 17), 32);
34 }
35}