1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */
18 
19 #ifndef GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_VARINT_H
20 #define GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_VARINT_H
21 
22 #include <grpc/support/port_platform.h>
23 
24 /* Helpers for hpack varint encoding */
25 
26 /* length of a value that needs varint tail encoding (it's bigger than can be
27    bitpacked into the opcode byte) - returned value includes the length of the
28    opcode byte */
29 uint32_t grpc_chttp2_hpack_varint_length(uint32_t tail_value);
30 
31 void grpc_chttp2_hpack_write_varint_tail(uint32_t tail_value, uint8_t* target,
32                                          uint32_t tail_length);
33 
34 /* maximum value that can be bitpacked with the opcode if the opcode has a
35    prefix
36    of length prefix_bits */
37 #define GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits) \
38   ((uint32_t)((1 << (8 - (prefix_bits))) - 1))
39 
40 /* length required to bitpack a value */
41 #define GRPC_CHTTP2_VARINT_LENGTH(n, prefix_bits) \
42   ((n) < GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits)   \
43        ? 1u                                       \
44        : grpc_chttp2_hpack_varint_length(         \
45              (n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits)))
46 
47 #define GRPC_CHTTP2_WRITE_VARINT(n, prefix_bits, prefix_or, target, length)   \
48   do {                                                                        \
49     uint8_t* tgt = target;                                                    \
50     if ((length) == 1u) {                                                     \
51       (tgt)[0] = (uint8_t)((prefix_or) | (n));                                \
52     } else {                                                                  \
53       (tgt)[0] =                                                              \
54           (prefix_or) | (uint8_t)GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits);      \
55       grpc_chttp2_hpack_write_varint_tail(                                    \
56           (n)-GRPC_CHTTP2_MAX_IN_PREFIX(prefix_bits), (tgt) + 1, (length)-1); \
57     }                                                                         \
58   } while (0)
59 
60 #endif /* GRPC_CORE_EXT_TRANSPORT_CHTTP2_TRANSPORT_VARINT_H */
61