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_ENCODING_H_
16 #define DRACO_CORE_VARINT_ENCODING_H_
17 
18 #include <type_traits>
19 
20 #include "draco/core/bit_utils.h"
21 #include "draco/core/encoder_buffer.h"
22 
23 namespace draco {
24 
25 // Encodes a specified integer as varint. Note that different coding is used
26 // when IntTypeT is an unsigned data type.
27 template <typename IntTypeT>
EncodeVarint(IntTypeT val,EncoderBuffer * out_buffer)28 bool EncodeVarint(IntTypeT val, EncoderBuffer *out_buffer) {
29   if (std::is_unsigned<IntTypeT>::value) {
30     // Coding of unsigned values.
31     // 0-6 bit - data
32     // 7 bit - next byte?
33     uint8_t out = 0;
34     out |= val & ((1 << 7) - 1);
35     if (val >= (1 << 7)) {
36       out |= (1 << 7);
37       if (!out_buffer->Encode(out)) {
38         return false;
39       }
40       if (!EncodeVarint<IntTypeT>(val >> 7, out_buffer)) {
41         return false;
42       }
43       return true;
44     }
45     if (!out_buffer->Encode(out)) {
46       return false;
47     }
48   } else {
49     // IntTypeT is a signed value. Convert to unsigned symbol and encode.
50     const typename std::make_unsigned<IntTypeT>::type symbol =
51         ConvertSignedIntToSymbol(val);
52     if (!EncodeVarint(symbol, out_buffer)) {
53       return false;
54     }
55   }
56   return true;
57 }
58 
59 }  // namespace draco
60 
61 #endif  // DRACO_CORE_VARINT_ENCODING_H_
62