Skip to main content

cbor_core/
format.rs

1/// Format for CBOR decoding or encoding.
2///
3/// Selected on [`DecodeOptions`](crate::DecodeOptions) to choose how
4/// input bytes are interpreted. All three formats decode to the same
5/// [`Value`](crate::Value) type.
6///
7/// | Variant | Description |
8/// |---|---|
9/// | [`Binary`](Self::Binary) | Standard CBOR binary encoding (RFC 8949). |
10/// | [`Hex`](Self::Hex) | Hex-encoded CBOR binary: each CBOR byte as two ASCII hex digits. |
11/// | [`Diagnostic`](Self::Diagnostic) | CBOR diagnostic notation (Section 8 of RFC 8949, Section 2.3.6 of CBOR::Core). |
12#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
13pub enum Format {
14    /// Standard CBOR binary encoding.
15    #[default]
16    Binary,
17    /// Hex-encoded CBOR binary. Each CBOR byte is represented as two ASCII
18    /// hex digits (upper or lower case).
19    Hex,
20    /// CBOR diagnostic notation (human-readable text).
21    Diagnostic,
22}
23
24/// Format for CBOR output produced by [`SequenceWriter`](crate::SequenceWriter).
25///
26/// Mirrors [`Format`] on the encode side, but adds output-only variants
27/// the decoder has no use for.
28///
29/// | Variant | Output |
30/// |---|---|
31/// | [`Binary`](Self::Binary) | Standard CBOR binary encoding. |
32/// | [`Hex`](Self::Hex) | Hex-encoded CBOR binary, lowercase. |
33/// | [`Diagnostic`](Self::Diagnostic) | Compact diagnostic notation. Sequence items are separated by `, `. |
34/// | [`DiagnosticPretty`](Self::DiagnosticPretty) | Pretty-printed diagnostic notation (`{:#?}`-style, indented). Sequence items are separated by `,\n`. |
35///
36/// `From<Format> for EncodeFormat` lets any [`Format`] pass through an
37/// `impl Into<EncodeFormat>` bound unchanged.
38#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
39pub enum EncodeFormat {
40    /// Standard CBOR binary encoding.
41    #[default]
42    Binary,
43    /// Hex-encoded CBOR binary, lowercase.
44    Hex,
45    /// Compact diagnostic notation.
46    Diagnostic,
47    /// Pretty-printed diagnostic notation (`{:#?}`-style).
48    DiagnosticPretty,
49}
50
51impl From<Format> for EncodeFormat {
52    fn from(format: Format) -> Self {
53        match format {
54            Format::Binary => Self::Binary,
55            Format::Hex => Self::Hex,
56            Format::Diagnostic => Self::Diagnostic,
57        }
58    }
59}