blob: 53ffd2d662539f86e530dbf1ca51552e936f3eb0 [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.
Alice Wangef999242023-05-22 11:14:59 +000029 BufferTooSmall(usize),
Alice Wang856d6562023-02-03 13:51:08 +000030 /// Platform error.
31 PlatformError,
Alice Wang856d6562023-02-03 13:51:08 +000032}
33
34/// This makes `DiceError` accepted by anyhow.
35#[cfg(feature = "std")]
36impl Error for DiceError {}
37
38impl fmt::Display for DiceError {
39 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
40 match self {
41 Self::InvalidInput => write!(f, "invalid input"),
Alice Wangef999242023-05-22 11:14:59 +000042 Self::BufferTooSmall(buffer_required_size) => {
43 write!(f, "buffer too small. Required {buffer_required_size} bytes.")
44 }
Alice Wang856d6562023-02-03 13:51:08 +000045 Self::PlatformError => write!(f, "platform error"),
Alice Wang856d6562023-02-03 13:51:08 +000046 }
47 }
48}
49
50/// DICE result type.
51pub type Result<T> = result::Result<T, DiceError>;
52
53/// Checks the given `DiceResult`. Returns an error if it's not OK.
Alice Wangef999242023-05-22 11:14:59 +000054pub(crate) fn check_result(result: DiceResult, buffer_required_size: usize) -> Result<()> {
Alice Wang856d6562023-02-03 13:51:08 +000055 match result {
56 DiceResult::kDiceResultOk => Ok(()),
57 DiceResult::kDiceResultInvalidInput => Err(DiceError::InvalidInput),
Alice Wangef999242023-05-22 11:14:59 +000058 DiceResult::kDiceResultBufferTooSmall => {
59 Err(DiceError::BufferTooSmall(buffer_required_size))
60 }
Alice Wang856d6562023-02-03 13:51:08 +000061 DiceResult::kDiceResultPlatformError => Err(DiceError::PlatformError),
62 }
63}