File indexing completed on 2024-05-12 05:43:27

0001 /*
0002     Copyright (C) 2015 Volker Krause <vkrause@kde.org>
0003 
0004     This program is free software; you can redistribute it and/or modify it
0005     under the terms of the GNU Library General Public License as published by
0006     the Free Software Foundation; either version 2 of the License, or (at your
0007     option) any later version.
0008 
0009     This program is distributed in the hope that it will be useful, but WITHOUT
0010     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0011     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
0012     License for more details.
0013 
0014     You should have received a copy of the GNU General Public License
0015     along with this program.  If not, see <https://www.gnu.org/licenses/>.
0016 */
0017 
0018 #include "dwarfleb128.h"
0019 
0020 namespace DwarfLEB128 {
0021 
0022 // see https://en.wikipedia.org/wiki/LEB128
0023 
0024 uint64_t decodeUnsigned(const char* data, int* size)
0025 {
0026     const auto begin = data;
0027     uint64_t result = 0;
0028     unsigned int shift = 0;
0029     uint8_t currentByte = 0;
0030 
0031     do {
0032         currentByte = *data++;
0033         result |= uint64_t(currentByte & 0x7f) << shift;
0034         shift += 7;
0035     } while (currentByte & 0x80);
0036 
0037     if (size)
0038         *size = data - begin;
0039 
0040     return result;
0041 }
0042 
0043 int64_t decodeSigned(const char* data, int* size)
0044 {
0045     const auto begin = data;
0046     int64_t result = 0;
0047     unsigned int shift = 0;
0048     uint8_t currentByte = 0;
0049 
0050     do {
0051         currentByte = *data++;
0052         result |= ((currentByte & 0x7f) << shift);
0053         shift += 7;
0054     } while (currentByte & 0x80);
0055 
0056     if (currentByte & 0x40)
0057         result |= uint64_t(-1) << shift;
0058 
0059     if (size)
0060         *size = data - begin;
0061 
0062     return result;
0063 }
0064 
0065 }