otopr/
impls.rs

1use bytes::BufMut;
2
3use crate::{
4    decoding::{Decodable, DecodingError},
5    encoding::Encodable,
6    traits::Signable,
7    wire_types::*,
8    Fixed32, Fixed64, VarInt,
9};
10
11macro_rules! signable {
12    ($($id:ident($storage: ty)),*) => {$(
13        impl Signable for $id {
14            type Storage = $storage;
15            type From = Self;
16            fn zigzag_encode(this: Self) -> $storage {
17                const BITS_M1: u32 = <$id>::BITS - 1;
18                ((this << 1) ^ (this >> BITS_M1)) as $storage
19            }
20        }
21    )*};
22    ($($id:ident($storage: ty) = $signed:ident),*) => {$(
23        impl Signable for $id {
24            type Storage = $storage;
25            type From = $signed;
26            fn zigzag_encode(this: $signed) -> $storage {
27                const BITS_M1: u32 = <$signed>::BITS - 1;
28                ((this << 1) ^ (this >> BITS_M1)) as $storage
29            }
30        }
31    )*};
32}
33
34signable!(i32(u32), i64(u64));
35signable!(Fixed32(u32) = i32, Fixed64(u32) = i64);
36
37crate::seal! {
38    for u64,
39    for u32,
40    for i64,
41    for i32,
42    for u16,
43    for u8,
44    for usize,
45    for Fixed32,
46    for Fixed64,
47}
48
49impl Encodable for str {
50    type Wire = LengthDelimitedWire;
51
52    fn encoded_size<V: VarInt>(&self, field_number: V) -> usize {
53        field_number.size() + self.len().size() + self.len()
54    }
55    fn encode(&self, s: &mut crate::encoding::ProtobufSerializer<impl BufMut>) {
56        s.write_str(self)
57    }
58}
59
60impl Encodable for bool {
61    type Wire = VarIntWire;
62
63    fn encoded_size<V: VarInt>(&self, field_number: V) -> usize {
64        field_number.size() + 1
65    }
66
67    fn encode(&self, s: &mut crate::encoding::ProtobufSerializer<impl BufMut>) {
68        s.write_u8(*self as u8);
69    }
70}
71
72impl Decodable<'_> for bool {
73    type Wire = VarIntWire;
74
75    fn decode<B: bytes::Buf>(
76        deserializer: &mut crate::decoding::Deserializer<'_, B>,
77    ) -> crate::decoding::Result<Self> {
78        match deserializer.get_u8() {
79            0b0000_0001 => Ok(true),
80            0b0000_0000 => Ok(false),
81            _ => Err(DecodingError::VarIntOverflow),
82        }
83    }
84}