blob: bb274977cfb971cc2f8f24ecf0ab0fec3df3088e [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;
19
20pub(crate) fn write<T>(ptr: *mut T, value: T) -> Result<(), AvbIOError> {
21 let ptr = to_nonnull(ptr)?;
22 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
23 unsafe {
24 *ptr.as_ptr() = value;
25 }
26 Ok(())
27}
28
29pub(crate) fn as_ref<'a, T>(ptr: *mut T) -> Result<&'a T, AvbIOError> {
30 let ptr = to_nonnull(ptr)?;
31 // SAFETY: It is safe as the raw pointer `ptr` is a nonnull pointer.
32 unsafe { Ok(ptr.as_ref()) }
33}
34
35pub(crate) fn to_nonnull<T>(ptr: *mut T) -> Result<NonNull<T>, AvbIOError> {
36 NonNull::new(ptr).ok_or(AvbIOError::NoSuchValue)
37}
38
39pub(crate) fn is_not_null<T>(ptr: *const T) -> Result<(), AvbIOError> {
40 if ptr.is_null() {
41 Err(AvbIOError::NoSuchValue)
42 } else {
43 Ok(())
44 }
45}
46
47pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> Result<usize, AvbIOError> {
48 num.try_into().map_err(|_| AvbIOError::InvalidValueSize)
49}
50
51pub(crate) fn usize_checked_add(x: usize, y: usize) -> Result<usize, AvbIOError> {
52 x.checked_add(y).ok_or(AvbIOError::InvalidValueSize)
53}