blob: 1b35c2265213564cd1ed36ff05c6b311d5ce832d [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
17use crate::error::AvbIOError;
18use core::ptr::NonNull;
Alice Wangeccdd392023-01-23 08:50:27 +000019use core::result;
Alice Wang8077a862023-01-18 16:06:37 +000020
Alice Wangeccdd392023-01-23 08:50:27 +000021pub(crate) type Result<T> = result::Result<T, AvbIOError>;
22
23pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<()> {
Alice Wang8077a862023-01-18 16:06:37 +000024 let ptr = to_nonnull(ptr)?;
25 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
26 unsafe {
27 *ptr.as_ptr() = value;
28 }
29 Ok(())
30}
31
Alice Wangeccdd392023-01-23 08:50:27 +000032pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T> {
Alice Wang8077a862023-01-18 16:06:37 +000033 let ptr = to_nonnull(ptr)?;
34 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
35 unsafe { Ok(ptr.as_ref()) }
36}
37
Alice Wangeccdd392023-01-23 08:50:27 +000038pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>> {
Alice Wang8077a862023-01-18 16:06:37 +000039 NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
40}
41
Alice Wangeccdd392023-01-23 08:50:27 +000042pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<()> {
Alice Wang8077a862023-01-18 16:06:37 +000043 if ptr.is_null() {
44 Err(AvbIOError::NoSuchValue)
45 } else {
46 Ok(())
47 }
48}
49
Alice Wangeccdd392023-01-23 08:50:27 +000050pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize> {
Alice Wang8077a862023-01-18 16:06:37 +000051 num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
52}
53
Alice Wangeccdd392023-01-23 08:50:27 +000054pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize> {
Alice Wang8077a862023-01-18 16:06:37 +000055 x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
56}