leb128.h revision f8ee788a64d60abd8f2d742a5fdedde054ecd910
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// LEB128 encoder and decoder for packed R_ARM_RELATIVE relocations. 6// 7// Run-length encoded R_ARM_RELATIVE relocations consist of a large number 8// of pairs of relatively small positive integer values. Encoding these as 9// LEB128 saves space. 10// 11// For more on LEB128 see http://en.wikipedia.org/wiki/LEB128. 12 13#ifndef TOOLS_RELOCATION_PACKER_SRC_LEB128_H_ 14#define TOOLS_RELOCATION_PACKER_SRC_LEB128_H_ 15 16#include <stdint.h> 17#include <unistd.h> 18#include <vector> 19 20namespace relocation_packer { 21 22// Encode packed words as a LEB128 byte stream. 23class Leb128Encoder { 24 public: 25 // Add a value to the encoding stream. 26 // |value| is the unsigned int to add. 27 void Enqueue(uint32_t value); 28 29 // Add a vector of values to the encoding stream. 30 // |values| is the vector of unsigned ints to add. 31 void EnqueueAll(const std::vector<uint32_t>& values); 32 33 // Retrieve the encoded representation of the values. 34 // |encoding| is the returned vector of encoded data. 35 void GetEncoding(std::vector<uint8_t>* encoding) { *encoding = encoding_; } 36 37 private: 38 // Growable vector holding the encoded LEB128 stream. 39 std::vector<uint8_t> encoding_; 40}; 41 42// Decode a LEB128 byte stream to produce packed words. 43class Leb128Decoder { 44 public: 45 // Create a new decoder for the given encoded stream. 46 // |encoding| is the vector of encoded data. 47 explicit Leb128Decoder(const std::vector<uint8_t>& encoding) 48 : encoding_(encoding), cursor_(0) { } 49 50 // Retrieve the next value from the encoded stream. 51 uint32_t Dequeue(); 52 53 // Retrieve all remaining values from the encoded stream. 54 // |values| is the vector of decoded data. 55 void DequeueAll(std::vector<uint32_t>* values); 56 57 private: 58 // Encoded LEB128 stream. 59 std::vector<uint8_t> encoding_; 60 61 // Cursor indicating the current stream retrieval point. 62 size_t cursor_; 63}; 64 65} // namespace relocation_packer 66 67#endif // TOOLS_RELOCATION_PACKER_SRC_LEB128_H_ 68