rmp/encode/
bin.rs

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