prost_bytes05/lib.rs
1#![doc(html_root_url = "https://docs.rs/prost/0.5.0")]
2
3mod error;
4mod message;
5mod types;
6
7#[doc(hidden)]
8pub mod encoding;
9
10pub use crate::error::{DecodeError, EncodeError};
11pub use crate::message::Message;
12
13use bytes::{Buf, BufMut};
14
15use crate::encoding::{decode_varint, encode_varint, encoded_len_varint};
16
17// See `encoding::DecodeContext` for more info.
18// 100 is the default recursion limit in the C++ implementation.
19#[cfg(not(feature = "no-recursion-limit"))]
20const RECURSION_LIMIT: u32 = 100;
21
22/// Encodes a length delimiter to the buffer.
23///
24/// See [Message.encode_length_delimited] for more info.
25///
26/// An error will be returned if the buffer does not have sufficient capacity to encode the
27/// delimiter.
28pub fn encode_length_delimiter<B>(length: usize, buf: &mut B) -> Result<(), EncodeError>
29where
30 B: BufMut,
31{
32 let length = length as u64;
33 let required = encoded_len_varint(length);
34 let remaining = buf.remaining_mut();
35 if required > remaining {
36 return Err(EncodeError::new(required, remaining));
37 }
38 encode_varint(length, buf);
39 Ok(())
40}
41
42/// Returns the encoded length of a length delimiter.
43///
44/// Applications may use this method to ensure sufficient buffer capacity before calling
45/// `encode_length_delimiter`. The returned size will be between 1 and 10, inclusive.
46pub fn length_delimiter_len(length: usize) -> usize {
47 encoded_len_varint(length as u64)
48}
49
50/// Decodes a length delimiter from the buffer.
51///
52/// This method allows the length delimiter to be decoded independently of the message, when the
53/// message is encoded with [Message.encode_length_delimited].
54///
55/// An error may be returned in two cases:
56///
57/// * If the supplied buffer contains fewer than 10 bytes, then an error indicates that more
58/// input is required to decode the full delimiter.
59/// * If the supplied buffer contains more than 10 bytes, then the buffer contains an invalid
60/// delimiter, and typically the buffer should be considered corrupt.
61pub fn decode_length_delimiter<B>(mut buf: B) -> Result<usize, DecodeError>
62where
63 B: Buf,
64{
65 let length = decode_varint(&mut buf)?;
66 if length > usize::max_value() as u64 {
67 return Err(DecodeError::new(
68 "length delimiter exceeds maximum usize value",
69 ));
70 }
71 Ok(length as usize)
72}
73
74// Re-export #[derive(Message, Enumeration, Oneof)].
75// Based on serde's equivalent re-export [1], but enabled by default.
76//
77// [1]: https://github.com/serde-rs/serde/blob/v1.0.89/serde/src/lib.rs#L245-L256
78#[cfg(feature = "prost-derive")]
79#[allow(unused_imports)]
80#[macro_use]
81extern crate prost_derive;
82#[cfg(feature = "prost-derive")]
83#[doc(hidden)]
84pub use prost_derive::*;