Skip to main content

BytesEncoding

Trait BytesEncoding 

Source
pub trait BytesEncoding: 'static {
    const NAME: &'static str;

    // Required methods
    fn encode(bytes: &[u8], out: &mut String);
    fn decode(s: &str) -> Result<Vec<u8>, Error>;
}
Expand description

An encoding of bytes as string.

Encodings are types which are not instantiated. They are used with BytesFormat::encoded and every encoding is an adapter which represents bytes as strings in the encoding (see the adapters documentation). With BytesFallback the encoding is only used in formats without native bytes.

use deser::adapters::BytesEncoding;
use deser::{Error, ErrorKind};

/// Writes bytes as decimal numbers separated by dots.
pub struct Dotted;

impl BytesEncoding for Dotted {
    const NAME: &'static str = "dotted";

    fn encode(bytes: &[u8], out: &mut String) {
        for (idx, byte) in bytes.iter().enumerate() {
            if idx > 0 {
                out.push('.');
            }
            out.push_str(&byte.to_string());
        }
    }

    fn decode(s: &str) -> Result<Vec<u8>, Error> {
        if s.is_empty() {
            return Ok(Vec::new());
        }
        s.split('.')
            .map(|x| {
                x.parse().map_err(|_| {
                    Error::new(ErrorKind::Unexpected, "invalid byte")
                })
            })
            .collect()
    }
}

Required Associated Constants§

Source

const NAME: &'static str

The name of the encoding.

The name is used in error messages and to compare BytesFormats.

Required Methods§

Source

fn encode(bytes: &[u8], out: &mut String)

Encodes bytes and appends them to the string.

Source

fn decode(s: &str) -> Result<Vec<u8>, Error>

Decodes a string.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl BytesEncoding for Base64

Source§

const NAME: &'static str = "base64"

Source§

impl BytesEncoding for Base64NoPad

Source§

const NAME: &'static str = "base64-nopad"

Source§

impl BytesEncoding for Base64Url

Source§

const NAME: &'static str = "base64url"

Source§

impl BytesEncoding for Base64UrlNoPad

Source§

const NAME: &'static str = "base64url-nopad"