fire_protobuf/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3
4mod varint;
5pub mod decode;
6pub mod encode;
7#[cfg(test)]
8pub mod test_util;
9#[cfg(test)]
10pub mod tests;
11
12use decode::{DecodeMessage, DecodeError};
13use encode::{MessageEncoder, EncodeMessage, EncodeError};
14
15pub use bytes;
16pub use codegen::*;
17
18
19pub fn from_slice<'a, T>(slice: &'a [u8]) -> Result<T, DecodeError>
20where T: DecodeMessage<'a> {
21	T::parse_from_bytes(slice)
22}
23
24pub fn to_vec<T>(msg: &mut T) -> Result<Vec<u8>, EncodeError>
25where T: EncodeMessage {
26	msg.write_to_bytes()
27}
28
29pub fn to_bytes_writer<T, W>(msg: &mut T, w: &mut W) -> Result<(), EncodeError>
30where
31	T: EncodeMessage,
32	W: bytes::BytesWrite
33{
34	let mut encoder = MessageEncoder::new(w);
35
36	msg.encode(None, &mut encoder)
37}
38
39// todo move this into a module
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum WireType {
42	Varint,
43	I32,
44	I64,
45	Len
46}
47
48impl WireType {
49	pub(crate) fn from_tag(tag: u64) -> Result<Self, DecodeError> {
50		let b = tag as u8 & 0b0000_0111;
51
52		match b {
53			0 => Ok(Self::Varint),
54			1 => Ok(Self::I64),
55			2 => Ok(Self::Len),
56			5 => Ok(Self::I32),
57			b => Err(DecodeError::InvalidWireType(b))
58		}
59	}
60
61	pub(crate) fn as_num(&self) -> u8 {
62		match self {
63			Self::Varint => 0,
64			Self::I64 => 1,
65			Self::Len => 2,
66			Self::I32 => 5
67		}
68	}
69
70	pub(crate) const fn can_be_packed(&self) -> bool {
71		matches!(self, Self::Varint | Self::I32 | Self::I64)
72	}
73
74	pub fn is_len(&self) -> bool {
75		matches!(self, Self::Len)
76	}
77}