blob: 7396edc159205b7a4f9531f7cf2d7f82f0917e92 [file] [log] [blame]
Alice Wangeacb7382023-06-05 12:53:54 +00001// Copyright 2023, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Utility functions.
16
17/// Flatten [[T; N]] into &[T]
18/// TODO: use slice::flatten when it graduates from experimental
19pub fn flatten<T, const N: usize>(original: &[[T; N]]) -> &[T] {
20 // SAFETY: no overflow because original (whose size is len()*N) is already in memory
21 let len = original.len() * N;
22 // SAFETY: [T] has the same layout as [T;N]
23 unsafe { core::slice::from_raw_parts(original.as_ptr().cast(), len) }
24}
25
26/// Computes the largest multiple of the provided alignment smaller or equal to the address.
27///
28/// Note: the result is undefined if alignment isn't a power of two.
29pub const fn unchecked_align_down(addr: usize, alignment: usize) -> usize {
30 addr & !(alignment - 1)
31}
32
33/// Computes the smallest multiple of the provided alignment larger or equal to the address.
34///
35/// Note: the result is undefined if alignment isn't a power of two and may wrap to 0.
36pub const fn unchecked_align_up(addr: usize, alignment: usize) -> usize {
37 unchecked_align_down(addr + alignment - 1, alignment)
38}
39
40/// Safe wrapper around unchecked_align_up() that validates its assumptions and doesn't wrap.
41pub const fn align_up(addr: usize, alignment: usize) -> Option<usize> {
42 if !alignment.is_power_of_two() {
43 None
44 } else if let Some(s) = addr.checked_add(alignment - 1) {
45 Some(unchecked_align_down(s, alignment))
46 } else {
47 None
48 }
49}
50
51/// Aligns the given address to the given alignment, if it is a power of two.
52///
53/// Returns `None` if the alignment isn't a power of two.
54#[allow(dead_code)] // Currently unused but might be needed again.
55const fn align_down(addr: usize, alignment: usize) -> Option<usize> {
56 if !alignment.is_power_of_two() {
57 None
58 } else {
59 Some(unchecked_align_down(addr, alignment))
60 }
61}
62
63/// Performs an integer division rounding up.
64///
65/// Note: Returns None if den isn't a power of two.
66pub const fn ceiling_div(num: usize, den: usize) -> Option<usize> {
67 let Some(r) = align_up(num, den) else {
68 return None;
69 };
70
71 r.checked_div(den)
72}