synta 0.2.4

ASN.1 parser, decoder, and encoder library with DER/BER support and C FFI
Documentation
//! Encoding trait

use crate::der::encoder::Encoder;
use crate::error::Result;

/// Trait for types that can be encoded to ASN.1.
///
/// # Implementing this trait
///
/// Both methods must be consistent: `encoded_len` must return **exactly** the
/// number of bytes that `encode` will write to the encoder.  If they disagree,
/// [`Encoder::encode_with_tag`] will write an incorrect length prefix, silently
/// producing malformed output.
///
/// A typical implementation computes `tag_len + length_field_len + value_len`,
/// where `length_field_len` is obtained via [`Length::Definite(n).encoded_len()`].
///
/// [`Encoder::encode_with_tag`]: crate::Encoder::encode_with_tag
/// [`Length::Definite(n).encoded_len()`]: crate::Length::encoded_len
pub trait Encode {
    /// Encode this value as ASN.1 TLV bytes into `encoder`.
    ///
    /// Writes exactly `self.encoded_len()?` bytes.
    fn encode(&self, encoder: &mut Encoder) -> Result<()>;

    /// Return the number of bytes that [`encode`] will write.
    ///
    /// The return value **must** be identical to the number of bytes written
    /// by a successful call to [`encode`].  Implementations that return an
    /// incorrect length will silently corrupt the encoded output when the
    /// value is nested inside a constructed element.
    ///
    /// [`encode`]: Self::encode
    fn encoded_len(&self) -> Result<usize>;
}

/// Blanket implementation of `Encode` for shared references.
///
/// Forwarding through `&T` lets callers pass a reference where an owned value
/// would otherwise be required — in particular, the generated code produced by
/// `#[derive(Asn1Sequence)]` and friends wraps fields in `ExplicitTag<&T>` /
/// `ImplicitTag<&T>` to avoid cloning the field value just for tagging.
impl<T: Encode> Encode for &T {
    fn encode(&self, encoder: &mut Encoder) -> Result<()> {
        (**self).encode(encoder)
    }

    fn encoded_len(&self) -> Result<usize> {
        (**self).encoded_len()
    }
}