rmp/encode/
bin.rs

1use super::RmpWrite;
2use crate::encode::{write_marker, ValueWriteError};
3use crate::Marker;
4
5/// Encodes and attempts to write the most efficient binary array length implementation to the given
6/// write, returning the marker used.
7///
8/// This function is useful when you want to get full control for writing the data itself, for
9/// example, when using non-blocking socket.
10///
11/// # Errors
12///
13/// This function will return `ValueWriteError` on any I/O error occurred while writing either the
14/// marker or the data.
15pub fn write_bin_len<W: RmpWrite>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError<W::Error>> {
16    let marker = if len < 256 {
17        Marker::Bin8
18    } else if len <= u16::MAX as u32 {
19        Marker::Bin16
20    } else {
21        Marker::Bin32
22    };
23    write_marker(&mut *wr, marker)?;
24    if marker == Marker::Bin8 {
25        wr.write_data_u8(len as u8)?;
26    } else if marker == Marker::Bin16 {
27        wr.write_data_u16(len as u16)?;
28    } else if marker == Marker::Bin32 {
29        wr.write_data_u32(len)?;
30    }
31    Ok(marker)
32}
33
34/// Encodes and attempts to write the most efficient binary implementation to the given `Write`.
35///
36/// # Errors
37///
38/// This function will return `ValueWriteError` on any I/O error occurred while writing either the
39/// marker or the data.
40// TODO: Docs, range check, example, visibility.
41pub fn write_bin<W: RmpWrite>(wr: &mut W, data: &[u8]) -> Result<(), ValueWriteError<W::Error>> {
42    write_bin_len(wr, data.len() as u32)?;
43    wr.write_bytes(data)
44        .map_err(ValueWriteError::InvalidDataWrite)
45}