[][src]Module framed::bytes

Sending and receiving slices of bytes.

Example usage from a std crate

See the decode_* and encode_* functions for simple uses with various input and output types.

The Sender struct writes encoded payloads to an inner std::io::Write instance, and the Receiver struct reads and decodes payloads from an inner std::io::Read instance.

let mut config = Config::default();

let payload = [1, 2, 3];

let mut encoded = vec![];
{
    let mut sender = config.clone().to_sender(&mut encoded);
    sender.send(&payload).expect("send ok");
}

// `encoded` now contains the encoded frame.

let mut receiver = config.clone().to_receiver(Cursor::new(encoded));
let decoded = receiver.recv().expect("recv ok");

assert_eq!(payload, *decoded);

Example usage from a no_std crate

The encode_to_slice and decode_from_slice functions offer an API for no_std crates that do not have a heap allocator available and cannot use std::io::Read or std::io::Write.

let mut codec = Config::default().to_codec();

// In a no_std crate without dynamic memory allocation we would typically
// know the maximum payload length, which we can use for payload buffers.
const MAX_PAYLOAD_LEN: usize = 10;

// The maximum payload length implies a maximum encoded frame length,
// which we can use for frame buffers.
//
// Using a calculated frame buffer length like this requires
// const fn, which is currently unstable and only available on nightly rust.
// Enable cargo feature flag "use_nightly" to use it.
const MAX_FRAME_LEN: usize = max_encoded_len(MAX_PAYLOAD_LEN);

let payload: [u8; 3] = [1, 2, 3];
assert!(payload.len() <= MAX_PAYLOAD_LEN);

let mut encoded_buf = [0u8; MAX_FRAME_LEN];
let encoded_len = codec.encode_to_slice(&payload, &mut encoded_buf)
                       .expect("encode ok");
let encoded = &encoded_buf[0..encoded_len];

// `encoded` now contains the encoded frame.

let mut decoded_buf = [0u8; MAX_PAYLOAD_LEN];
let decoded_len = codec.decode_to_slice(&encoded, &mut decoded_buf)
                       .expect("decode ok");
let decoded = &decoded_buf[0..decoded_len];

assert_eq!(payload, *decoded);

Structs

Codec

Contains methods for encoding and decoding byte slices with a specific configuration.

Config

Configurable options for encoding and decoding byte slices using a builder pattern.

Receiver

Receives encoded frames from an inner std::io::Read instance.

Sender

Sends encoded frames over an inner std::io::Write instance.

Enums

Checksum

A checksum algorithm configuration to use when encoding data.

Functions

max_decoded_len

Returns an upper bound for the decoded length of the payload within a frame with the encoded length supplied.

max_encoded_len

Returns an upper bound for the encoded length of a frame with the payload length supplied.