cedar_policy/proto/traits.rs
1/*
2 * Copyright Cedar Contributors
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 * https://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/// Trait allowing serializing and deserializing in protobuf format
18pub trait Protobuf: Sized {
19 /// Encode into protobuf format. Returns a freshly-allocated buffer containing binary data.
20 fn encode(&self) -> Vec<u8>;
21 /// Decode the binary data in `buf`, producing something of type `Self`
22 fn decode(buf: impl prost::bytes::Buf) -> Result<Self, prost::DecodeError>;
23}
24
25/// Encode `thing` into `buf` using the protobuf format `M`
26///
27/// `Err` is only returned if `buf` has insufficient space.
28#[allow(dead_code)] // experimental feature, we might have use for this one in the future
29pub(crate) fn encode<M: prost::Message>(
30 thing: impl Into<M>,
31 buf: &mut impl prost::bytes::BufMut,
32) -> Result<(), prost::EncodeError> {
33 thing.into().encode(buf)
34}
35
36/// Encode `thing` into a freshly-allocated buffer using the protobuf format `M`
37pub(crate) fn encode_to_vec<M: prost::Message>(thing: impl Into<M>) -> Vec<u8> {
38 thing.into().encode_to_vec()
39}
40
41use std::default::Default;
42
43/// Decode something of type `T` from `buf` using the protobuf format `M`
44pub(crate) fn decode<M: prost::Message + Default, T: for<'a> From<&'a M>>(
45 buf: impl prost::bytes::Buf,
46) -> Result<T, prost::DecodeError> {
47 M::decode(buf).map(|m| T::from(&m))
48}
49
50/// Decode something of type `T` from `buf` using the protobuf format `M`
51pub(crate) fn try_decode<M: prost::Message + Default, E, T: for<'a> TryFrom<&'a M, Error = E>>(
52 buf: impl prost::bytes::Buf,
53) -> Result<Result<T, E>, prost::DecodeError> {
54 M::decode(buf).map(|m| T::try_from(&m))
55}