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