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