1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "elf_traits.h"
12 namespace relocation_packer
{
14 // Empty constructor and destructor to silence chromium-style.
15 template <typename uint_t
>
16 Leb128Encoder
<uint_t
>::Leb128Encoder() { }
18 template <typename uint_t
>
19 Leb128Encoder
<uint_t
>::~Leb128Encoder() { }
21 // Add a single value to the encoding. Values are encoded with variable
22 // length. The least significant 7 bits of each byte hold 7 bits of data,
23 // and the most significant bit is set on each byte except the last.
24 template <typename uint_t
>
25 void Leb128Encoder
<uint_t
>::Enqueue(uint_t value
) {
26 uint_t uvalue
= static_cast<uint_t
>(value
);
28 const uint8_t byte
= uvalue
& 127;
30 encoding_
.push_back((uvalue
? 128 : 0) | byte
);
34 // Add a vector of values to the encoding.
35 template <typename uint_t
>
36 void Leb128Encoder
<uint_t
>::EnqueueAll(const std::vector
<uint_t
>& values
) {
37 for (size_t i
= 0; i
< values
.size(); ++i
) {
42 // Create a new decoder for the given encoded stream.
43 template <typename uint_t
>
44 Leb128Decoder
<uint_t
>::Leb128Decoder(const std::vector
<uint8_t>& encoding
, size_t start_with
) {
49 // Empty destructor to silence chromium-style.
50 template <typename uint_t
>
51 Leb128Decoder
<uint_t
>::~Leb128Decoder() { }
53 // Decode and retrieve a single value from the encoding. Read forwards until
54 // a byte without its most significant bit is found, then read the 7 bit
55 // fields of the bytes spanned to re-form the value.
56 template <typename uint_t
>
57 uint_t Leb128Decoder
<uint_t
>::Dequeue() {
63 // Loop until we reach a byte with its high order bit clear.
65 byte
= encoding_
[cursor_
++];
66 value
|= static_cast<uint_t
>(byte
& 127) << shift
;
73 // Decode and retrieve all remaining values from the encoding.
74 template <typename uint_t
>
75 void Leb128Decoder
<uint_t
>::DequeueAll(std::vector
<uint_t
>* values
) {
76 while (cursor_
< encoding_
.size()) {
77 values
->push_back(Dequeue());
81 template class Leb128Encoder
<uint32_t>;
82 template class Leb128Encoder
<uint64_t>;
84 template class Leb128Decoder
<uint32_t>;
85 template class Leb128Decoder
<uint64_t>;
87 } // namespace relocation_packer