/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rmp-0.8.15/src/encode/str.rs
Line | Count | Source |
1 | | use super::{write_marker, RmpWrite}; |
2 | | use crate::encode::ValueWriteError; |
3 | | use 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. |
12 | 0 | pub fn write_str_len<W: RmpWrite>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError<W::Error>> { |
13 | 0 | let marker = if len < 32 { |
14 | 0 | Marker::FixStr(len as u8) |
15 | 0 | } else if len < 256 { |
16 | 0 | Marker::Str8 |
17 | 0 | } else if u16::try_from(len).is_ok() { |
18 | 0 | Marker::Str16 |
19 | | } else { |
20 | 0 | Marker::Str32 |
21 | | }; |
22 | | |
23 | 0 | write_marker(wr, marker)?; |
24 | 0 | if marker == Marker::Str8 { |
25 | 0 | wr.write_data_u8(len as u8)?; |
26 | 0 | } |
27 | 0 | if marker == Marker::Str16 { |
28 | 0 | wr.write_data_u16(len as u16)?; |
29 | 0 | } |
30 | 0 | if marker == Marker::Str32 { |
31 | 0 | wr.write_data_u32(len)?; |
32 | 0 | } |
33 | 0 | Ok(marker) |
34 | 0 | } |
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. |
44 | 0 | pub fn write_str<W: RmpWrite>(wr: &mut W, data: &str) -> Result<(), ValueWriteError<W::Error>> { |
45 | 0 | write_str_len(wr, data.len() as u32)?; |
46 | 0 | wr.write_bytes(data.as_bytes()).map_err(ValueWriteError::InvalidDataWrite) |
47 | 0 | } |