Alice Wang | 8077a86 | 2023-01-18 16:06:37 +0000 | [diff] [blame] | 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 | |
David Pursell | b59bcc4 | 2023-11-10 16:59:19 -0800 | [diff] [blame] | 17 | use avb::{IoError, IoResult}; |
Alice Wang | 8077a86 | 2023-01-18 16:06:37 +0000 | [diff] [blame] | 18 | |
David Pursell | b59bcc4 | 2023-11-10 16:59:19 -0800 | [diff] [blame] | 19 | pub(crate) fn is_not_null<T>(ptr: *const T) -> IoResult<()> { |
Alice Wang | 8077a86 | 2023-01-18 16:06:37 +0000 | [diff] [blame] | 20 | if ptr.is_null() { |
David Pursell | b59bcc4 | 2023-11-10 16:59:19 -0800 | [diff] [blame] | 21 | Err(IoError::NoSuchValue) |
Alice Wang | 8077a86 | 2023-01-18 16:06:37 +0000 | [diff] [blame] | 22 | } else { |
| 23 | Ok(()) |
| 24 | } |
| 25 | } |
| 26 | |
David Pursell | b59bcc4 | 2023-11-10 16:59:19 -0800 | [diff] [blame] | 27 | pub(crate) fn to_usize<T: TryInto<usize>>(num: T) -> IoResult<usize> { |
| 28 | num.try_into().map_err(|_| IoError::InvalidValueSize) |
Alice Wang | 8077a86 | 2023-01-18 16:06:37 +0000 | [diff] [blame] | 29 | } |
| 30 | |
David Pursell | b59bcc4 | 2023-11-10 16:59:19 -0800 | [diff] [blame] | 31 | pub(crate) fn usize_checked_add(x: usize, y: usize) -> IoResult<usize> { |
| 32 | x.checked_add(y).ok_or(IoError::InvalidValueSize) |
Alice Wang | 8077a86 | 2023-01-18 16:06:37 +0000 | [diff] [blame] | 33 | } |