blob: 202ee9a3397e88360ae00830cfa94102b8067af5 [file] [log] [blame]
Brian Silverman8fce7482020-01-05 13:18:21 -08001/*----------------------------------------------------------------------------*/
2/* Copyright (c) 2015-2019 FIRST. All Rights Reserved. */
3/* Open Source Software - may be modified and shared by FRC teams. The code */
4/* must be accompanied by the FIRST BSD license file in the root directory of */
5/* the project. */
6/*----------------------------------------------------------------------------*/
7
8#include "wpi/leb128.h"
9
10#include "wpi/raw_istream.h"
11
12namespace wpi {
13
14uint64_t SizeUleb128(uint64_t val) {
15 size_t count = 0;
16 do {
17 val >>= 7;
18 ++count;
19 } while (val != 0);
20 return count;
21}
22
23uint64_t WriteUleb128(SmallVectorImpl<char>& dest, uint64_t val) {
24 size_t count = 0;
25
26 do {
27 unsigned char byte = val & 0x7f;
28 val >>= 7;
29
30 if (val != 0)
31 byte |= 0x80; // mark this byte to show that more bytes will follow
32
33 dest.push_back(byte);
34 count++;
35 } while (val != 0);
36
37 return count;
38}
39
40uint64_t ReadUleb128(const char* addr, uint64_t* ret) {
41 uint64_t result = 0;
42 int shift = 0;
43 size_t count = 0;
44
45 while (1) {
46 unsigned char byte = *reinterpret_cast<const unsigned char*>(addr);
47 addr++;
48 count++;
49
50 result |= (byte & 0x7f) << shift;
51 shift += 7;
52
53 if (!(byte & 0x80)) break;
54 }
55
56 *ret = result;
57
58 return count;
59}
60
61bool ReadUleb128(raw_istream& is, uint64_t* ret) {
62 uint64_t result = 0;
63 int shift = 0;
64
65 while (1) {
66 unsigned char byte;
67 is.read(reinterpret_cast<char*>(&byte), 1);
68 if (is.has_error()) return false;
69
70 result |= (byte & 0x7f) << shift;
71 shift += 7;
72
73 if (!(byte & 0x80)) break;
74 }
75
76 *ret = result;
77
78 return true;
79}
80
81} // namespace wpi