rmp/encode/
str.rs

1use super::{write_marker, RmpWrite};
2use crate::encode::ValueWriteError;
3use crate::Marker;
4
5/// Encodes and attempts to write the most efficient string length implementation to the given
6/// write, returning the marker used.
7///
8/// # Errors
9///
10/// This function will return `ValueWriteError` on any I/O error occurred while writing either the
11/// marker or the data.
12pub fn write_str_len<W: RmpWrite>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError<W::Error>> {
13    let marker = if len < 32 {
14        Marker::FixStr(len as u8)
15    } else if len < 256 {
16        Marker::Str8
17    } else if len <= u16::MAX as u32 {
18        Marker::Str16
19    } else {
20        Marker::Str32
21    };
22
23    write_marker(wr, marker)?;
24    if marker == Marker::Str8 {
25        wr.write_data_u8(len as u8)?;
26    }
27    if marker == Marker::Str16 {
28        wr.write_data_u16(len as u16)?;
29    }
30    if marker == Marker::Str32 {
31        wr.write_data_u32(len)?;
32    }
33    Ok(marker)
34}
35
36/// Encodes and attempts to write the most efficient string binary representation to the
37/// given `Write`.
38///
39/// # Errors
40///
41/// This function will return `ValueWriteError` on any I/O error occurred while writing either the
42/// marker or the data.
43// TODO: Docs, range check, example, visibility.
44pub fn write_str<W: RmpWrite>(wr: &mut W, data: &str) -> Result<(), ValueWriteError<W::Error>> {
45    write_str_len(wr, data.len() as u32)?;
46    wr.write_bytes(data.as_bytes()).map_err(ValueWriteError::InvalidDataWrite)
47}