leb128.cc revision 116680a4aac90f2aa7413d9095a592090648e557
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.
4
5// TODO(simonb): Extend for 64-bit target libraries.
6
7#include "leb128.h"
8
9#include <stdint.h>
10#include <vector>
11
12namespace relocation_packer {
13
14// Empty constructor and destructor to silence chromium-style.
15Leb128Encoder::Leb128Encoder() { }
16Leb128Encoder::~Leb128Encoder() { }
17
18// Add a single value to the encoding.  Values are encoded with variable
19// length.  The least significant 7 bits of each byte hold 7 bits of data,
20// and the most significant bit is set on each byte except the last.
21void Leb128Encoder::Enqueue(uint32_t value) {
22  while (value > 127) {
23    encoding_.push_back((1 << 7) | (value & 127));
24    value >>= 7;
25  }
26  encoding_.push_back(value);
27}
28
29// Add a vector of values to the encoding.
30void Leb128Encoder::EnqueueAll(const std::vector<uint32_t>& values) {
31  for (size_t i = 0; i < values.size(); ++i)
32    Enqueue(values[i]);
33}
34
35// Create a new decoder for the given encoded stream.
36Leb128Decoder::Leb128Decoder(const std::vector<uint8_t>& encoding) {
37  encoding_ = encoding;
38  cursor_ = 0;
39}
40
41// Empty destructor to silence chromium-style.
42Leb128Decoder::~Leb128Decoder() { }
43
44// Decode and retrieve a single value from the encoding.  Read forwards until
45// a byte without its most significant bit is found, then read the 7 bit
46// fields of the bytes spanned to re-form the value.
47uint32_t Leb128Decoder::Dequeue() {
48  size_t extent = cursor_;
49  while (encoding_[extent] >> 7)
50    extent++;
51
52  uint32_t value = 0;
53  for (size_t i = extent; i > cursor_; --i) {
54    value = (value << 7) | (encoding_[i] & 127);
55  }
56  value = (value << 7) | (encoding_[cursor_] & 127);
57
58  cursor_ = extent + 1;
59  return value;
60}
61
62// Decode and retrieve all remaining values from the encoding.
63void Leb128Decoder::DequeueAll(std::vector<uint32_t>* values) {
64  while (cursor_ < encoding_.size())
65    values->push_back(Dequeue());
66}
67
68}  // namespace relocation_packer
69