#include "segment_bank.hpp" #include namespace segment { int Bank::copy(int handle, std::size_t source, std::size_t destination, std::size_t length) { Attachment *entry = attachment(handle); if (entry == nullptr || !retained(entry->id)) { return -9; } if (entry->readonly) { return -13; } Bytes &data = object(entry->id)->data; if (check_range(data.size(), source, length) != 0) { return -22; } if (check_range(data.size(), destination, length) != 0) { return -22; } Bytes saved(data.begin() + source, data.begin() + source + length); for (std::size_t index = 0; index < length; ++index) { data[destination + index] = saved[index]; } return 0; } int decimal(const std::string &text, std::uint64_t &out) { if (text.empty()) { return -22; } for (char byte : text) { if (byte < '0' || byte > '9') { return -22; } } std::uint64_t value = 0; const std::uint64_t limit = std::numeric_limits::max(); for (char byte : text) { unsigned digit = static_cast(byte - '0'); if (value > (limit - digit) / 10) { return -34; } value = value * 10 + digit; } out = value; return 0; } namespace { int digit_value(char byte) { if (byte >= '0' && byte <= '9') { return byte - '0'; } if (byte >= 'a' && byte <= 'f') { return byte - 'a' + 10; } if (byte >= 'A' && byte <= 'F') { return byte - 'A' + 10; } return -1; } } int hex_decode(const std::string &text, Bytes &out) { if (text.size() % 2 != 0) { return -22; } Bytes result; result.reserve(text.size() / 2); for (std::size_t index = 0; index < text.size(); index += 2) { int high = digit_value(text[index]); int low = digit_value(text[index + 1]); if (high < 0 || low < 0) { return -22; } result.push_back(static_cast(high * 16 + low)); } out.swap(result); return 0; } std::string hex_encode(const Bytes &input) { const char digits[] = "0123456789abcdef"; std::string result; result.reserve(input.size() * 2); for (unsigned char byte : input) { result.push_back(digits[byte >> 4]); result.push_back(digits[byte & 15]); } return result; } }