Port Android relocation packer to chromium build
[chromium-blink-merge.git] / third_party / android_platform / bionic / tools / relocation_packer / src / leb128.cc
blob101c5577863bf94e8b8c745a60abff5ed5272a67
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.
5 #include "leb128.h"
7 #include <stdint.h>
8 #include <vector>
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);
27 do {
28 const uint8_t byte = uvalue & 127;
29 uvalue >>= 7;
30 encoding_.push_back((uvalue ? 128 : 0) | byte);
31 } while (uvalue);
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) {
38 Enqueue(values[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) {
45 encoding_ = encoding;
46 cursor_ = 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() {
58 uint_t value = 0;
60 size_t shift = 0;
61 uint8_t byte;
63 // Loop until we reach a byte with its high order bit clear.
64 do {
65 byte = encoding_[cursor_++];
66 value |= static_cast<uint_t>(byte & 127) << shift;
67 shift += 7;
68 } while (byte & 128);
70 return value;
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