codec_cbor/general/
contract.rs1use super::encode::encode_generated;
6use super::encode_contract::float;
7use super::error::{error, CborError, ErrorReason};
8use super::{EncodedCbor, Limits, Profile};
9use codec_proto::generated::proto::reallyme::codec::v1 as proto;
10
11impl TryFrom<&proto::CodecGeneralCborOptions> for Profile {
12 type Error = CborError;
13 fn try_from(value: &proto::CodecGeneralCborOptions) -> Result<Self, Self::Error> {
14 let invalid = || error(ErrorReason::UnsupportedPolicy);
15 Self::new(
16 value.serialization.as_known().ok_or_else(invalid)?,
17 value.lengths.as_known().ok_or_else(invalid)?,
18 value.floats.as_known().ok_or_else(invalid)?,
19 value.ordering.as_known().ok_or_else(invalid)?,
20 )
21 }
22}
23
24impl TryFrom<&proto::CodecGeneralCborOptions> for Limits {
25 type Error = CborError;
26 fn try_from(value: &proto::CodecGeneralCborOptions) -> Result<Self, Self::Error> {
27 let mut limits = Self::default();
28 macro_rules! apply {
31 ($field:ident, $setter:ident) => {
32 if let Some(value) = value.$field {
33 limits = limits.$setter(
34 usize::try_from(value).map_err(|_| error(ErrorReason::InvalidLimit))?,
35 )?;
36 }
37 };
38 }
39 apply!(input_bytes, with_input_bytes);
40 apply!(output_bytes, with_output_bytes);
41 apply!(depth, with_depth);
42 apply!(nodes, with_nodes);
43 apply!(entries, with_entries);
44 apply!(byte_string_bytes, with_byte_string_bytes);
45 apply!(text_bytes, with_text_bytes);
46 apply!(work, with_work);
47 Ok(limits)
48 }
49}
50
51pub fn encode_value(
53 value: &proto::CodecGeneralCborValue,
54 profile: Profile,
55 limits: Limits,
56) -> Result<EncodedCbor, CborError> {
57 encode_generated(value, profile, limits)
58}
59
60pub fn float_properties(
62 value: &proto::CodecGeneralCborFloat,
63) -> Result<proto::CodecGeneralCborFloatProperties, CborError> {
64 let native = float(value)?;
65 Ok(proto::CodecGeneralCborFloatProperties {
66 value: Some(proto::CodecGeneralCborFloat {
67 width: native.width().into(),
68 bits: native.bits(),
69 })
70 .into(),
71 shortest_width: native.shortest().into(),
72 finite: native.is_finite(),
73 nan: native.is_nan(),
74 widened_binary64_bits: native.to_f64().to_bits(),
75 })
76}
77
78pub fn float_equivalent(
80 left: &proto::CodecGeneralCborFloat,
81 right: &proto::CodecGeneralCborFloat,
82) -> Result<bool, CborError> {
83 Ok(float(left)?.equivalent(&float(right)?))
84}