Skip to main content

aws_smithy_cbor/
codec.rs

1/*
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0
4 */
5
6//! CBOR codec implementation for schema-based serialization.
7
8use aws_smithy_schema::codec::Codec;
9
10mod deserializer;
11mod serializer;
12
13pub use deserializer::CborDeserializer;
14pub use serializer::{CborSerializer, StructPrefix};
15
16/// Configuration for CBOR codec behavior.
17#[derive(Debug, Clone)]
18pub struct CborCodecSettings {
19    max_depth: u32,
20    enforce_strictness: bool,
21    use_definite_lengths: bool,
22}
23
24impl CborCodecSettings {
25    /// Uses definite-length encoding for collections whose element or entry
26    /// count is supplied by the caller. Unknown lengths remain indefinite.
27    /// Disabled by default.
28    pub fn use_definite_lengths(mut self, value: bool) -> Self {
29        self.use_definite_lengths = value;
30        self
31    }
32
33    /// Rejects trailing bytes after top-level containers and truncated nested structures.
34    /// Disabled by default to preserve client deserialization behavior.
35    pub fn enforce_strictness(mut self, value: bool) -> Self {
36        self.enforce_strictness = value;
37        self
38    }
39
40    /// Maximum aggregate nesting depth the deserializer will accept.
41    pub fn max_depth(&self) -> u32 {
42        self.max_depth
43    }
44}
45
46impl Default for CborCodecSettings {
47    fn default() -> Self {
48        Self {
49            max_depth: 128,
50            enforce_strictness: false,
51            use_definite_lengths: false,
52        }
53    }
54}
55
56/// CBOR codec for schema-based serialization and deserialization.
57#[derive(Debug)]
58pub struct CborCodec {
59    settings: CborCodecSettings,
60}
61
62impl CborCodec {
63    /// Creates a new CBOR codec with the given settings.
64    pub fn new(settings: CborCodecSettings) -> Self {
65        Self { settings }
66    }
67}
68
69impl Default for CborCodec {
70    fn default() -> Self {
71        Self::new(CborCodecSettings::default())
72    }
73}
74
75impl Codec for CborCodec {
76    type Serializer = CborSerializer;
77    type Deserializer<'a> = CborDeserializer<'a>;
78
79    fn create_serializer(&self) -> Self::Serializer {
80        CborSerializer::new().with_definite_lengths(self.settings.use_definite_lengths)
81    }
82
83    fn create_deserializer<'a>(&self, input: &'a [u8]) -> Self::Deserializer<'a> {
84        CborDeserializer::new(input, self.settings.max_depth)
85            .with_strictness(self.settings.enforce_strictness)
86    }
87}