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 let mut profile = 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 if let Some(equality) = value.map_key_equality {
22 profile = profile.with_map_key_equality(equality.as_known().ok_or_else(invalid)?)?;
23 }
24 if let Some(policy) = value.nan_policy {
25 profile = profile.with_nan_policy(policy.as_known().ok_or_else(invalid)?)?;
26 }
27 Ok(profile)
28 }
29}
30
31impl TryFrom<&proto::CodecGeneralCborOptions> for Limits {
32 type Error = CborError;
33 fn try_from(value: &proto::CodecGeneralCborOptions) -> Result<Self, Self::Error> {
34 let mut limits = Self::default();
35 macro_rules! apply {
38 ($field:ident, $setter:ident) => {
39 if let Some(value) = value.$field {
40 limits = limits.$setter(
41 usize::try_from(value).map_err(|_| error(ErrorReason::InvalidLimit))?,
42 )?;
43 }
44 };
45 }
46 apply!(input_bytes, with_input_bytes);
47 apply!(output_bytes, with_output_bytes);
48 apply!(depth, with_depth);
49 apply!(nodes, with_nodes);
50 apply!(entries, with_entries);
51 apply!(byte_string_bytes, with_byte_string_bytes);
52 apply!(text_bytes, with_text_bytes);
53 apply!(work, with_work);
54 Ok(limits)
55 }
56}
57
58pub fn encode_value(
60 value: &proto::CodecGeneralCborValue,
61 profile: Profile,
62 limits: Limits,
63) -> Result<EncodedCbor, CborError> {
64 encode_generated(value, profile, limits)
65}
66
67pub fn float_properties(
69 value: &proto::CodecGeneralCborFloat,
70) -> Result<proto::CodecGeneralCborFloatProperties, CborError> {
71 let native = float(value)?;
72 Ok(proto::CodecGeneralCborFloatProperties {
73 value: Some(proto::CodecGeneralCborFloat {
74 width: native.width().into(),
75 bits: native.bits(),
76 })
77 .into(),
78 shortest_width: native.shortest().into(),
79 finite: native.is_finite(),
80 nan: native.is_nan(),
81 widened_binary64_bits: native.to_f64().to_bits(),
82 })
83}
84
85pub fn float_equivalent(
87 left: &proto::CodecGeneralCborFloat,
88 right: &proto::CodecGeneralCborFloat,
89) -> Result<bool, CborError> {
90 Ok(float(left)?.equivalent(&float(right)?))
91}