1 /*
2  * Copyright (c) Facebook, Inc. and its affiliates.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef THRIFT_UTIL_VARINTUTILS_H_
18 #define THRIFT_UTIL_VARINTUTILS_H_ 1
19 
20 #include <stdint.h>
21 
22 namespace apache {
23 namespace thrift {
24 
25 namespace util {
26 
27 /**
28  * Read an i16 from the wire as a varint. The MSB of each byte is set
29  * if there is another byte to follow. This can read up to 3 bytes.
30  */
31 uint32_t readVarint16(
32     uint8_t const* ptr, int16_t* i16, uint8_t const* boundary);
33 
34 /**
35  * Read an i32 from the wire as a varint. The MSB of each byte is set
36  * if there is another byte to follow. This can read up to 5 bytes.
37  */
38 uint32_t readVarint32(
39     uint8_t const* ptr, int32_t* i32, uint8_t const* boundary);
40 
41 /**
42  * Read an i64 from the wire as a proper varint. The MSB of each byte is set
43  * if there is another byte to follow. This can read up to 10 bytes.
44  * Caller is responsible for advancing ptr after call.
45  */
46 uint32_t readVarint64(
47     uint8_t const* ptr, int64_t* i64, uint8_t const* boundary);
48 
49 /**
50  * Write an i32 as a varint. Results in 1-5 bytes on the wire.
51  */
52 uint32_t writeVarint32(uint32_t n, uint8_t* pkt);
53 
54 /**
55  * Convert n into a zigzag int. This allows negative numbers to be
56  * represented compactly as a varint.
57  */
58 constexpr uint32_t i32ToZigzag(const int32_t n);
59 
60 constexpr uint64_t i64ToZigzag(const int64_t l);
61 
62 /**
63  * Convert from zigzag long to long.
64  */
65 int64_t zigzagToI64(uint64_t n);
66 
67 int32_t zigzagToI32(uint32_t n);
68 
69 } // namespace util
70 } // namespace thrift
71 } // namespace apache
72 
73 #include <thrift/lib/cpp/util/VarintUtils-inl.h>
74 
75 #endif // THRIFT_UTIL_VARINTUTILS_H_
76