quick_protobuf/sizeofs.rs
1//! A module to compute the binary size of data once encoded
2//!
3//! This module is used primilarly when implementing the `MessageWrite::get_size`
4
5/// Computes the binary size of the varint encoded u64
6///
7/// https://developers.google.com/protocol-buffers/docs/encoding
8pub fn sizeof_varint(v: u64) -> usize {
9 match v {
10 0x0..=0x7F => 1,
11 0x80..=0x3FFF => 2,
12 0x4000..=0x1FFFFF => 3,
13 0x200000..=0xFFFFFFF => 4,
14 0x10000000..=0x7FFFFFFFF => 5,
15 0x0800000000..=0x3FFFFFFFFFF => 6,
16 0x040000000000..=0x1FFFFFFFFFFFF => 7,
17 0x02000000000000..=0xFFFFFFFFFFFFFF => 8,
18 0x0100000000000000..=0x7FFFFFFFFFFFFFFF => 9,
19 _ => 10,
20 }
21}
22
23/// Computes the binary size of a variable length chunk of data (wire type 2)
24///
25/// The total size is the varint encoded length size plus the length itself
26/// https://developers.google.com/protocol-buffers/docs/encoding
27pub fn sizeof_len(len: usize) -> usize {
28 sizeof_varint(len as u64) + len
29}
30
31/// Computes the binary size of the varint encoded i32
32pub fn sizeof_int32(v: i32) -> usize {
33 sizeof_varint(v as u64)
34}
35
36/// Computes the binary size of the varint encoded i64
37pub fn sizeof_int64(v: i64) -> usize {
38 sizeof_varint(v as u64)
39}
40
41/// Computes the binary size of the varint encoded uint32
42pub fn sizeof_uint32(v: u32) -> usize {
43 sizeof_varint(v as u64)
44}
45
46/// Computes the binary size of the varint encoded uint64
47pub fn sizeof_uint64(v: u64) -> usize {
48 sizeof_varint(v)
49}
50
51/// Computes the binary size of the varint encoded sint32
52pub fn sizeof_sint32(v: i32) -> usize {
53 sizeof_varint(((v << 1) ^ (v >> 31)) as u64)
54}
55
56/// Computes the binary size of the varint encoded sint64
57pub fn sizeof_sint64(v: i64) -> usize {
58 sizeof_varint(((v << 1) ^ (v >> 63)) as u64)
59}
60
61/// Computes the binary size of the varint encoded bool (always = 1)
62pub fn sizeof_bool(_: bool) -> usize {
63 1
64}
65
66/// Computes the binary size of the varint encoded enum
67pub fn sizeof_enum(v: i32) -> usize {
68 sizeof_int32(v)
69}