GameApi 28
Library used by GameApi Builder tool
Loading...
Searching...
No Matches
varint_decoding.h
Go to the documentation of this file.
1// Copyright 2016 The Draco Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15#ifndef DRACO_CORE_VARINT_DECODING_H_
16#define DRACO_CORE_VARINT_DECODING_H_
17
18#include <type_traits>
19
22
23namespace draco {
24
25namespace {
26
27// Decodes a specified unsigned integer as varint. |depth| is the current
28// recursion call depth. The first call to the function must be 1.
29template <typename IntTypeT>
30bool DecodeVarintUnsigned(int depth, IntTypeT *out_val, DecoderBuffer *buffer) {
31 constexpr IntTypeT max_depth = sizeof(IntTypeT) + 1 + (sizeof(IntTypeT) >> 3);
32 if (depth > max_depth) {
33 return false;
34 }
35 // Coding of unsigned values.
36 // 0-6 bit - data
37 // 7 bit - next byte?
38 uint8_t in;
39 if (!buffer->Decode(&in)) {
40 return false;
41 }
42 if (in & (1 << 7)) {
43 // Next byte is available, decode it first.
44 if (!DecodeVarintUnsigned<IntTypeT>(depth + 1, out_val, buffer)) {
45 return false;
46 }
47 // Append decoded info from this byte.
48 *out_val <<= 7;
49 *out_val |= in & ((1 << 7) - 1);
50 } else {
51 // Last byte reached
52 *out_val = in;
53 }
54 return true;
55}
56
57} // namespace
58
59// Decodes a specified integer as varint. Note that the IntTypeT must be the
60// same as the one used in the corresponding EncodeVarint() call.
61// out_val is undefined if this returns false.
62template <typename IntTypeT>
63bool DecodeVarint(IntTypeT *out_val, DecoderBuffer *buffer) {
64 if (std::is_unsigned<IntTypeT>::value) {
65 if (!DecodeVarintUnsigned<IntTypeT>(1, out_val, buffer)) {
66 return false;
67 }
68 } else {
69 // IntTypeT is a signed value. Decode the symbol and convert to signed.
70 typename std::make_unsigned<IntTypeT>::type symbol;
71 if (!DecodeVarintUnsigned(1, &symbol, buffer)) {
72 return false;
73 }
74 *out_val = ConvertSymbolToSignedInt(symbol);
75 }
76 return true;
77}
78
79} // namespace draco
80
81#endif // DRACO_CORE_VARINT_DECODING_H_
Definition decoder_buffer.h:30
Definition attribute_octahedron_transform.cc:21
bool DecodeVarint(IntTypeT *out_val, DecoderBuffer *buffer)
Definition varint_decoding.h:63
std::make_signed< IntTypeT >::type ConvertSymbolToSignedInt(IntTypeT val)
Definition bit_utils.h:108