forked from ethereum/solidity
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LEB128.h
59 lines (49 loc) · 1.48 KB
/
LEB128.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
This file is part of solidity.
solidity is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
solidity is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
#pragma once
#include <libsolutil/Common.h>
namespace solidity::util
{
inline bytes lebEncode(uint64_t _n)
{
bytes encoded;
while (_n > 0x7f)
{
encoded.emplace_back(uint8_t(0x80 | (_n & 0x7f)));
_n >>= 7;
}
encoded.emplace_back(_n);
return encoded;
}
// signed right shift is an arithmetic right shift
static_assert((-1 >> 1) == -1, "Arithmetic shift not supported.");
inline bytes lebEncodeSigned(int64_t _n)
{
// Based on https://github.com/llvm/llvm-project/blob/master/llvm/include/llvm/Support/LEB128.h
bytes result;
bool more;
do
{
uint8_t v = _n & 0x7f;
_n >>= 7;
more = !((((_n == 0) && ((v & 0x40) == 0)) || ((_n == -1) && ((v & 0x40) != 0))));
if (more)
v |= 0x80; // Mark this byte to show that more bytes will follow.
result.emplace_back(v);
}
while (more);
return result;
}
}