Alice Wang | facc2b8 | 2023-10-05 14:05:47 +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 | //! Utility functions for CBOR serialization/deserialization. |
| 16 | |
Alice Wang | 5dddeea | 2023-10-13 12:56:22 +0000 | [diff] [blame^] | 17 | #![cfg_attr(not(feature = "std"), no_std)] |
| 18 | |
| 19 | extern crate alloc; |
| 20 | |
Alice Wang | facc2b8 | 2023-10-05 14:05:47 +0000 | [diff] [blame] | 21 | use alloc::vec::Vec; |
| 22 | use coset::{CoseError, Result}; |
| 23 | use serde::{de::DeserializeOwned, Serialize}; |
| 24 | |
| 25 | /// Serializes the given data to a CBOR-encoded byte vector. |
Alice Wang | 5dddeea | 2023-10-13 12:56:22 +0000 | [diff] [blame^] | 26 | pub fn serialize<T: ?Sized + Serialize>(v: &T) -> Result<Vec<u8>> { |
Alice Wang | facc2b8 | 2023-10-05 14:05:47 +0000 | [diff] [blame] | 27 | let mut data = Vec::new(); |
| 28 | ciborium::into_writer(v, &mut data)?; |
| 29 | Ok(data) |
| 30 | } |
| 31 | |
| 32 | /// Deserializes the given type from a CBOR-encoded byte slice, failing if any extra |
| 33 | /// data remains after the type has been read. |
Alice Wang | 5dddeea | 2023-10-13 12:56:22 +0000 | [diff] [blame^] | 34 | pub fn deserialize<T: DeserializeOwned>(mut data: &[u8]) -> Result<T> { |
Alice Wang | facc2b8 | 2023-10-05 14:05:47 +0000 | [diff] [blame] | 35 | let res = ciborium::from_reader(&mut data)?; |
| 36 | if data.is_empty() { |
| 37 | Ok(res) |
| 38 | } else { |
| 39 | Err(CoseError::ExtraneousData) |
| 40 | } |
| 41 | } |