[cbor] Separate cbor conversion functions in an independent lib
This allows callers from both std and nostd environment to
convert to/from CBOR-encoded data.
Bug: 303807447
Test: atest libservice_vm_requests.test
Change-Id: Ib2052f28779290165941cb2cf7ecc9ca566472af
diff --git a/libs/cborutil/Android.bp b/libs/cborutil/Android.bp
new file mode 100644
index 0000000..4758c4b
--- /dev/null
+++ b/libs/cborutil/Android.bp
@@ -0,0 +1,42 @@
+package {
+ default_applicable_licenses: ["Android-Apache-2.0"],
+}
+
+rust_defaults {
+ name: "libcbor_util_defaults",
+ crate_name: "cbor_util",
+ srcs: ["src/lib.rs"],
+ defaults: ["avf_build_flags_rust"],
+ prefer_rlib: true,
+ apex_available: [
+ "com.android.virt",
+ ],
+}
+
+rust_library_rlib {
+ name: "libcbor_util_nostd",
+ defaults: ["libcbor_util_defaults"],
+ no_stdlibs: true,
+ stdlibs: [
+ "libcompiler_builtins.rust_sysroot",
+ "libcore.rust_sysroot",
+ ],
+ rustlibs: [
+ "libciborium_nostd",
+ "libcoset_nostd",
+ "libserde_nostd",
+ ],
+}
+
+rust_library {
+ name: "libcbor_util",
+ defaults: ["libcbor_util_defaults"],
+ features: [
+ "std",
+ ],
+ rustlibs: [
+ "libciborium",
+ "libcoset",
+ "libserde",
+ ],
+}
diff --git a/libs/cborutil/src/lib.rs b/libs/cborutil/src/lib.rs
new file mode 100644
index 0000000..2ec5af4
--- /dev/null
+++ b/libs/cborutil/src/lib.rs
@@ -0,0 +1,41 @@
+// Copyright 2023, The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//! Utility functions for CBOR serialization/deserialization.
+
+#![cfg_attr(not(feature = "std"), no_std)]
+
+extern crate alloc;
+
+use alloc::vec::Vec;
+use coset::{CoseError, Result};
+use serde::{de::DeserializeOwned, Serialize};
+
+/// Serializes the given data to a CBOR-encoded byte vector.
+pub fn serialize<T: ?Sized + Serialize>(v: &T) -> Result<Vec<u8>> {
+ let mut data = Vec::new();
+ ciborium::into_writer(v, &mut data)?;
+ Ok(data)
+}
+
+/// Deserializes the given type from a CBOR-encoded byte slice, failing if any extra
+/// data remains after the type has been read.
+pub fn deserialize<T: DeserializeOwned>(mut data: &[u8]) -> Result<T> {
+ let res = ciborium::from_reader(&mut data)?;
+ if data.is_empty() {
+ Ok(res)
+ } else {
+ Err(CoseError::ExtraneousData)
+ }
+}