Files
thehub/libs/utils/streaming/StreamingUtils.cpp

103 lines
2.7 KiB
C++

/*
* This file is part of the Flowee project
* Copyright (C) 2016-2025 Tom Zander <tom@flowee.org>
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "StreamingUtils.h"
#include <cassert>
#include <cstring>
#include <limits>
#include <sstream>
#include <iomanip>
int Streaming::writeCompactSize(char *data, uint64_t value)
{
int size = 1;
if (value < 253) {
// nothing to do
}
else if (value <= std::numeric_limits<unsigned short>::max()) {
uint16_t copy = static_cast<uint16_t>(value);
memcpy(data + 1, &copy, 2);
size += 2;
value = 253;
}
else if (value <= std::numeric_limits<unsigned int>::max()) {
uint32_t copy = static_cast<uint32_t>(value);
memcpy(data + 1, &copy, 4);
size += 4;
value = 254;
}
else {
memcpy(data + 1, &value, 8);
size += 8;
value = 255;
}
*data = static_cast<uint8_t>(value);
return size;
}
uint64_t Streaming::readCompactSize(const char **data, const char *end)
{
if (end <= *data)
return 0;
uint8_t x = *(*data);
if (x < 253) {
(*data)++;
return x;
}
if (x == 253) {
if (end <= (*data) + 3) {
*data = end;
return 0;
}
(*data)++;
uint64_t answer = *reinterpret_cast<const uint16_t*>(*data);
*data += 2;
return answer;
}
if (x == 254) {
if (end <= (*data) + 5) {
*data = end;
return 0;
}
(*data)++;
uint64_t answer = *reinterpret_cast<const uint32_t*>(*data);
*data += 4;
return answer;
}
assert(x == 255);
if (end <= (*data) + 9) {
*data = end;
return 0;
}
(*data)++;
uint64_t answer = *reinterpret_cast<const uint64_t*>(*data);
*data += 8;
return answer;
}
std::string Streaming::bytesToHex(const std::vector<char> &bytes)
{
std::ostringstream oss;
oss << std::hex << std::setfill('0');
for (char c : bytes) {
unsigned char byte = static_cast<unsigned char>(c);
oss << std::setw(2) << static_cast<unsigned int>(byte);
}
return oss.str();
}