1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 #include "pw_varint/varint.h"
22 extern "C" size_t pw_VarintEncode(uint64_t integer,
26 std::byte* buffer = static_cast<std::byte*>(output);
29 if (written >= output_size) {
33 // Grab 7 bits; the eighth bit is set to 1 to indicate more data coming.
34 buffer[written++] = static_cast<std::byte>(integer) | std::byte(0x80);
36 } while (integer != 0u);
38 buffer[written - 1] &= std::byte(0x7f); // clear the top bit of the last byte
42 extern "C" size_t pw_VarintZigZagEncode(int64_t integer,
45 return pw_VarintEncode(ZigZagEncode(integer), output, output_size);
48 extern "C" size_t pw_VarintDecode(const void* input,
51 uint64_t decoded_value = 0;
52 uint_fast8_t count = 0;
53 const std::byte* buffer = static_cast<const std::byte*>(input);
55 // The largest 64-bit ints require 10 B.
56 const size_t max_count = std::min(kMaxVarint64SizeBytes, input_size);
59 if (count >= max_count) {
63 // Add the bottom seven bits of the next byte to the result.
64 decoded_value |= static_cast<uint64_t>(buffer[count] & std::byte(0x7f))
67 // Stop decoding if the top bit is not set.
68 if ((buffer[count++] & std::byte(0x80)) == std::byte(0)) {
73 *output = decoded_value;
77 extern "C" size_t pw_VarintZigZagDecode(const void* input,
81 size_t bytes = pw_VarintDecode(input, input_size, &value);
82 *output = ZigZagDecode(value);
86 extern "C" size_t pw_VarintEncodedSize(uint64_t integer) {
87 return EncodedSize(integer);
90 extern "C" size_t pw_VarintZigZagEncodedSize(int64_t integer) {
91 return ZigZagEncodedSize(integer);