blob: b4f099b747b0646dffc42f83bf78053ecaee6f08 [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
David Pursellb59bcc42023-11-10 16:59:19 -080017use avb::{IoError, IoResult};
Alice Wang8077a862023-01-18 16:06:37 +000018
David Pursellb59bcc42023-11-10 16:59:19 -080019pub(crate) fn is_not_null<T>(ptr: *const T) -> IoResult<()> {
Alice Wang8077a862023-01-18 16:06:37 +000020 if ptr.is_null() {
David Pursellb59bcc42023-11-10 16:59:19 -080021 Err(IoError::NoSuchValue)
Alice Wang8077a862023-01-18 16:06:37 +000022 } else {
23 Ok(())
24 }
25}
26
David Pursellb59bcc42023-11-10 16:59:19 -080027pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> IoResult<usize> {
28 num.try_into().map_err(|_| IoError::InvalidValueSize)
Alice Wang8077a862023-01-18 16:06:37 +000029}
30
David Pursellb59bcc42023-11-10 16:59:19 -080031pub(crate) fn usize_checked_add(x: usize, y: usize) -> IoResult<usize> {
32 x.checked_add(y).ok_or(IoError::InvalidValueSize)
Alice Wang8077a862023-01-18 16:06:37 +000033}