Move [SU]LEB128 encoding to a utility header.
[oota-llvm.git] / include / llvm / Support / LEB128.h
1 //===- llvm/Support/LEB128.h - [SU]LEB128 utility functions -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares some utility functions for encoding SLEB128 and
11 // ULEB128 values.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_SYSTEM_LEB128_H
16 #define LLVM_SYSTEM_LEB128_H
17
18 #include <llvm/Support/raw_ostream.h>
19
20 namespace llvm {
21
22 /// Utility function to encode a SLEB128 value.
23 static inline void encodeSLEB128(int64_t Value, raw_ostream &OS) {
24   bool More;
25   do {
26     uint8_t Byte = Value & 0x7f;
27     // NOTE: this assumes that this signed shift is an arithmetic right shift.
28     Value >>= 7;
29     More = !((((Value == 0 ) && ((Byte & 0x40) == 0)) ||
30               ((Value == -1) && ((Byte & 0x40) != 0))));
31     if (More)
32       Byte |= 0x80; // Mark this byte that that more bytes will follow.
33     OS << char(Byte);
34   } while (More);
35 }
36
37 /// Utility function to encode a ULEB128 value.
38 static inline void encodeULEB128(uint64_t Value, raw_ostream &OS,
39                                  unsigned Padding = 0) {
40   do {
41     uint8_t Byte = Value & 0x7f;
42     Value >>= 7;
43     if (Value != 0 || Padding != 0)
44       Byte |= 0x80; // Mark this byte that that more bytes will follow.
45     OS << char(Byte);
46   } while (Value != 0);
47
48   // Pad with 0x80 and emit a null byte at the end.
49   if (Padding != 0) {
50     for (; Padding != 1; --Padding)
51       OS << '\x80';
52     OS << '\x00';
53   }
54 }
55
56 }  // namespace llvm
57
58 #endif  // LLVM_SYSTEM_LEB128_H