blob: 7fe60153915dcb3853c1f1b6f3d210f32f3f005b [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
Alice Wang4be4dd02023-06-07 07:50:40 +000017use core::ops::Range;
18
Alice Wanga3971062023-06-13 11:48:53 +000019/// Create &CStr out of &str literal
20#[macro_export]
21macro_rules! cstr {
22 ($str:literal) => {{
23 core::ffi::CStr::from_bytes_with_nul(concat!($str, "\0").as_bytes()).unwrap()
24 }};
25}
26
Alice Wangeacb7382023-06-05 12:53:54 +000027/// Flatten [[T; N]] into &[T]
28/// TODO: use slice::flatten when it graduates from experimental
29pub fn flatten<T, const N: usize>(original: &[[T; N]]) -> &[T] {
30 // SAFETY: no overflow because original (whose size is len()*N) is already in memory
31 let len = original.len() * N;
32 // SAFETY: [T] has the same layout as [T;N]
33 unsafe { core::slice::from_raw_parts(original.as_ptr().cast(), len) }
34}
35
36/// Computes the largest multiple of the provided alignment smaller or equal to the address.
37///
38/// Note: the result is undefined if alignment isn't a power of two.
39pub const fn unchecked_align_down(addr: usize, alignment: usize) -> usize {
40 addr & !(alignment - 1)
41}
42
43/// Computes the smallest multiple of the provided alignment larger or equal to the address.
44///
45/// Note: the result is undefined if alignment isn't a power of two and may wrap to 0.
46pub const fn unchecked_align_up(addr: usize, alignment: usize) -> usize {
47 unchecked_align_down(addr + alignment - 1, alignment)
48}
49
50/// Safe wrapper around unchecked_align_up() that validates its assumptions and doesn't wrap.
51pub const fn align_up(addr: usize, alignment: usize) -> Option<usize> {
52 if !alignment.is_power_of_two() {
53 None
54 } else if let Some(s) = addr.checked_add(alignment - 1) {
55 Some(unchecked_align_down(s, alignment))
56 } else {
57 None
58 }
59}
60
61/// Aligns the given address to the given alignment, if it is a power of two.
62///
63/// Returns `None` if the alignment isn't a power of two.
64#[allow(dead_code)] // Currently unused but might be needed again.
65const fn align_down(addr: usize, alignment: usize) -> Option<usize> {
66 if !alignment.is_power_of_two() {
67 None
68 } else {
69 Some(unchecked_align_down(addr, alignment))
70 }
71}
72
73/// Performs an integer division rounding up.
74///
75/// Note: Returns None if den isn't a power of two.
76pub const fn ceiling_div(num: usize, den: usize) -> Option<usize> {
77 let Some(r) = align_up(num, den) else {
78 return None;
79 };
80
81 r.checked_div(den)
82}
Alice Wang4be4dd02023-06-07 07:50:40 +000083
84/// Trait to check containment of one range within another.
85pub trait RangeExt {
86 /// Returns true if `self` is contained within the `other` range.
87 fn is_within(&self, other: &Self) -> bool;
88
89 /// Returns true if `self` overlaps with the `other` range.
90 fn overlaps(&self, other: &Self) -> bool;
91}
92
93impl<T: PartialOrd> RangeExt for Range<T> {
94 fn is_within(&self, other: &Self) -> bool {
95 self.start >= other.start && self.end <= other.end
96 }
97
98 fn overlaps(&self, other: &Self) -> bool {
99 self.start < other.end && other.start < self.end
100 }
101}