blob: 9cf2ae887cc6b8a1551bd9c56d73201d81fcd451 [file] [log] [blame]
Alice Wang856d6562023-02-03 13:51:08 +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//! Errors and relating functions thrown in this library.
16
17use open_dice_cbor_bindgen::DiceResult;
18use std::{fmt, result};
19
20#[cfg(feature = "std")]
21use std::error::Error;
22
23/// Error type used by DICE.
24#[derive(Debug)]
25pub enum DiceError {
26 /// Provided input was invalid.
27 InvalidInput,
28 /// Provided buffer was too small.
29 BufferTooSmall,
30 /// Platform error.
31 PlatformError,
32 /// Input string has an interior nul byte.
33 /// TODO(b/267575445): Remove this error once we change the param of
34 /// `format_config_descriptor to take &CStr.
35 #[cfg(feature = "std")]
36 CStrNulError,
37 /// The allocation of a ZVec failed.
38 #[cfg(feature = "std")]
39 ZVecError(keystore2_crypto::zvec::Error),
40}
41
42#[cfg(feature = "std")]
43impl From<keystore2_crypto::zvec::Error> for DiceError {
44 fn from(e: keystore2_crypto::zvec::Error) -> Self {
45 Self::ZVecError(e)
46 }
47}
48
49/// This makes `DiceError` accepted by anyhow.
50#[cfg(feature = "std")]
51impl Error for DiceError {}
52
53impl fmt::Display for DiceError {
54 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
55 match self {
56 Self::InvalidInput => write!(f, "invalid input"),
57 Self::BufferTooSmall => write!(f, "buffer too small"),
58 Self::PlatformError => write!(f, "platform error"),
59 #[cfg(feature = "std")]
60 Self::CStrNulError => write!(f, "input string has an interior nul byte"),
61 #[cfg(feature = "std")]
62 Self::ZVecError(e) => write!(f, "ZVec allocation failed {e}"),
63 }
64 }
65}
66
67/// DICE result type.
68pub type Result<T> = result::Result<T, DiceError>;
69
70/// Checks the given `DiceResult`. Returns an error if it's not OK.
71pub fn check_result(result: DiceResult) -> Result<()> {
72 match result {
73 DiceResult::kDiceResultOk => Ok(()),
74 DiceResult::kDiceResultInvalidInput => Err(DiceError::InvalidInput),
75 DiceResult::kDiceResultBufferTooSmall => Err(DiceError::BufferTooSmall),
76 DiceResult::kDiceResultPlatformError => Err(DiceError::PlatformError),
77 }
78}