/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rmp-0.8.14/src/encode/bin.rs
Line | Count | Source |
1 | | use super::RmpWrite; |
2 | | use crate::encode::{write_marker, ValueWriteError}; |
3 | | use 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. |
15 | 0 | pub fn write_bin_len<W: RmpWrite>(wr: &mut W, len: u32) -> Result<Marker, ValueWriteError<W::Error>> { |
16 | 0 | let marker = if len < 256 { |
17 | 0 | Marker::Bin8 |
18 | 0 | } else if len <= u16::MAX as u32 { |
19 | 0 | Marker::Bin16 |
20 | | } else { |
21 | 0 | Marker::Bin32 |
22 | | }; |
23 | 0 | write_marker(&mut *wr, marker)?; |
24 | 0 | if marker == Marker::Bin8 { |
25 | 0 | wr.write_data_u8(len as u8)?; |
26 | 0 | } else if marker == Marker::Bin16 { |
27 | 0 | wr.write_data_u16(len as u16)?; |
28 | 0 | } else if marker == Marker::Bin32 { |
29 | 0 | wr.write_data_u32(len)?; |
30 | 0 | } |
31 | 0 | Ok(marker) |
32 | 0 | } |
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. |
41 | 0 | pub fn write_bin<W: RmpWrite>(wr: &mut W, data: &[u8]) -> Result<(), ValueWriteError<W::Error>> { |
42 | 0 | write_bin_len(wr, data.len() as u32)?; |
43 | 0 | wr.write_bytes(data) |
44 | 0 | .map_err(ValueWriteError::InvalidDataWrite) |
45 | 0 | } |