1 /* 2 * Copyright (C) 2024 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 //! Helper functions that includes data transformation for AIDL types. 18 19 /// Macro to create enums that can easily be used as cose labels for serialization 20 /// It expects the macro definition to have the following form: 21 /// 22 /// cose_enum_gen! { 23 /// enum CoseEnumName { 24 /// CoseEnumField1 = value1, 25 /// CoseEnumField2 = value2, 26 /// } 27 /// } 28 #[macro_export] 29 macro_rules! cose_enum_gen { 30 (enum $name:ident {$($field:ident = $field_val:literal),+ $(,)*}) => { 31 enum $name { 32 $($field = $field_val),+ 33 } 34 35 impl TryFrom<i64> for $name { 36 type Error = hwcryptohal_common::err::HwCryptoError; 37 38 fn try_from(value: i64) -> Result<Self, Self::Error> { 39 match value { 40 $(x if x == $name::$field as i64 => Ok($name::$field)),+, 41 _ => Err(hwcrypto_err!(SERIALIZATION_ERROR, "unsupported COSE enum label val {}", value)), 42 } 43 } 44 } 45 46 impl TryFrom<ciborium::value::Integer> for $name { 47 type Error = coset::CoseError; 48 49 fn try_from(value: ciborium::value::Integer) -> Result<Self, Self::Error> { 50 let value: i64 = value.try_into()?; 51 Ok(value.try_into().map_err(|_| coset::CoseError::EncodeFailed)?) 52 } 53 } 54 } 55 } 56