rmp/encode/
str.rs

1use std::io::Write;
2
3use Marker;
4use encode::ValueWriteError;
5use super::{write_marker, write_data_u8, write_data_u16, write_data_u32};
6
7/// Encodes and attempts to write the most efficient string length implementation to the given
8/// write, returning the marker used.
9///
10/// # Errors
11///
12/// This function will return `ValueWriteError` on any I/O error occurred while writing either the
13/// marker or the data.
14pub fn write_str_len<W: Write>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError> {
15    if len < 32 {
16        try!(write_marker(wr, Marker::FixStr(len as u8)));
17        Ok(Marker::FixStr(len as u8))
18    } else if len < 256 {
19        try!(write_marker(wr, Marker::Str8));
20        try!(write_data_u8(wr, len as u8));
21        Ok(Marker::Str8)
22    } else if len < 65536 {
23        try!(write_marker(wr, Marker::Str16));
24        try!(write_data_u16(wr, len as u16));
25        Ok(Marker::Str16)
26    } else {
27        try!(write_marker(wr, Marker::Str32));
28        try!(write_data_u32(wr, len));
29        Ok(Marker::Str32)
30    }
31}
32
33/// Encodes and attempts to write the most efficient string binary representation to the
34/// 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_str<W: Write>(wr: &mut W, data: &str) -> Result<(), ValueWriteError> {
42    try!(write_str_len(wr, data.len() as u32));
43    wr.write_all(data.as_bytes()).map_err(ValueWriteError::InvalidDataWrite)
44}