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