blob: 2ec5af47d0a9a1dbd4f4eb4f61dd32e122c1bf42 [file] [log] [blame]
Alice Wangfacc2b82023-10-05 14:05:47 +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//! Utility functions for CBOR serialization/deserialization.
16
Alice Wang5dddeea2023-10-13 12:56:22 +000017#![cfg_attr(not(feature = "std"), no_std)]
18
19extern crate alloc;
20
Alice Wangfacc2b82023-10-05 14:05:47 +000021use alloc::vec::Vec;
22use coset::{CoseError, Result};
23use serde::{de::DeserializeOwned, Serialize};
24
25/// Serializes the given data to a CBOR-encoded byte vector.
Alice Wang5dddeea2023-10-13 12:56:22 +000026pub fn serialize<T: ?Sized + Serialize>(v: &T) -> Result<Vec<u8>> {
Alice Wangfacc2b82023-10-05 14:05:47 +000027 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 Wang5dddeea2023-10-13 12:56:22 +000034pub fn deserialize<T: DeserializeOwned>(mut data: &[u8]) -> Result<T> {
Alice Wangfacc2b82023-10-05 14:05:47 +000035 let res = ciborium::from_reader(&mut data)?;
36 if data.is_empty() {
37 Ok(res)
38 } else {
39 Err(CoseError::ExtraneousData)
40 }
41}