blob: f4f15e11f084c619019536513acd36425df99a68 [file] [log] [blame]
Alice Wang8077a862023-01-18 16:06:37 +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//! Common utility functions.
16
Alice Wang8077a862023-01-18 16:06:37 +000017use core::ptr::NonNull;
Alice Wangeccdd392023-01-23 08:50:27 +000018use core::result;
Alice Wang8077a862023-01-18 16:06:37 +000019
David Pursella7c727b2023-08-14 16:24:40 -070020pub(crate) type Result<T> = result::Result<T, avb::IoError>;
Alice Wangeccdd392023-01-23 08:50:27 +000021
22pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<()> {
Alice Wang8077a862023-01-18 16:06:37 +000023 let ptr = to_nonnull(ptr)?;
Alice Wangf2752862023-01-18 11:51:25 +000024 // SAFETY: It is safe as the raw pointer `ptr` is a non-null pointer.
Alice Wang8077a862023-01-18 16:06:37 +000025 unsafe {
26 *ptr.as_ptr() = value;
27 }
28 Ok(())
29}
30
Alice Wangeccdd392023-01-23 08:50:27 +000031pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T> {
Alice Wang8077a862023-01-18 16:06:37 +000032 let ptr = to_nonnull(ptr)?;
Alice Wangf2752862023-01-18 11:51:25 +000033 // SAFETY: It is safe as the raw pointer `ptr` is a non-null pointer.
Alice Wang8077a862023-01-18 16:06:37 +000034 unsafe { Ok(ptr.as_ref()) }
35}
36
Alice Wangeccdd392023-01-23 08:50:27 +000037pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>> {
David Pursella7c727b2023-08-14 16:24:40 -070038 NonNull::new(ptr).ok_or(avb::IoError::NoSuchValue)
Alice Wang8077a862023-01-18 16:06:37 +000039}
40
Alice Wangeccdd392023-01-23 08:50:27 +000041pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<()> {
Alice Wang8077a862023-01-18 16:06:37 +000042 if ptr.is_null() {
David Pursella7c727b2023-08-14 16:24:40 -070043 Err(avb::IoError::NoSuchValue)
Alice Wang8077a862023-01-18 16:06:37 +000044 } else {
45 Ok(())
46 }
47}
48
Alice Wangeccdd392023-01-23 08:50:27 +000049pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize> {
David Pursella7c727b2023-08-14 16:24:40 -070050 num.try_into().map_err(|_| avb::IoError::InvalidValueSize)
Alice Wang8077a862023-01-18 16:06:37 +000051}
52
Alice Wangeccdd392023-01-23 08:50:27 +000053pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize> {
David Pursella7c727b2023-08-14 16:24:40 -070054 x.checked_add(y).ok_or(avb::IoError::InvalidValueSize)
Alice Wang8077a862023-01-18 16:06:37 +000055}