|
| 1 | +/** |
| 2 | + * SPDX-License-Identifier: GPL-2.0-or-later |
| 3 | + * |
| 4 | + * This file is part of osm2pgsql (https://osm2pgsql.org/). |
| 5 | + * |
| 6 | + * Copyright (C) 2006-2025 by the osm2pgsql developer community. |
| 7 | + * For a full list of authors see the git log. |
| 8 | + */ |
| 9 | + |
| 10 | +#include "hex.hpp" |
| 11 | + |
| 12 | +#include <array> |
| 13 | +#include <cassert> |
| 14 | +#include <stdexcept> |
| 15 | + |
| 16 | +namespace util { |
| 17 | + |
| 18 | +void encode_hex(std::string const &in, std::string *out) |
| 19 | +{ |
| 20 | + assert(out); |
| 21 | + |
| 22 | + constexpr char const *const LOOKUP_HEX = "0123456789ABCDEF"; |
| 23 | + |
| 24 | + for (auto const c : in) { |
| 25 | + unsigned int const num = static_cast<unsigned char>(c); |
| 26 | + (*out) += LOOKUP_HEX[(num >> 4U) & 0xfU]; |
| 27 | + (*out) += LOOKUP_HEX[num & 0xfU]; |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +std::string encode_hex(std::string const &in) |
| 32 | +{ |
| 33 | + std::string result; |
| 34 | + result.reserve(in.size() * 2); |
| 35 | + encode_hex(in, &result); |
| 36 | + return result; |
| 37 | +} |
| 38 | + |
| 39 | +namespace { |
| 40 | + |
| 41 | +constexpr std::array<char, 256> const HEX_TABLE = { |
| 42 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 43 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 44 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 45 | + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, |
| 46 | + |
| 47 | + 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 48 | + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 49 | + 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, |
| 50 | +}; |
| 51 | + |
| 52 | +} // anonymous namespace |
| 53 | + |
| 54 | +unsigned char decode_hex_char(char c) noexcept |
| 55 | +{ |
| 56 | + // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-constant-array-index) |
| 57 | + return HEX_TABLE[static_cast<std::size_t>(static_cast<unsigned char>(c))]; |
| 58 | +} |
| 59 | + |
| 60 | +std::string decode_hex(std::string_view hex_string) |
| 61 | +{ |
| 62 | + if (hex_string.size() % 2 != 0) { |
| 63 | + throw std::runtime_error{"Invalid wkb: Not a valid hex string"}; |
| 64 | + } |
| 65 | + |
| 66 | + std::string wkb; |
| 67 | + wkb.reserve(hex_string.size() / 2); |
| 68 | + |
| 69 | + // NOLINTNEXTLINE(llvm-qualified-auto, readability-qualified-auto) |
| 70 | + for (auto hex = hex_string.begin(); hex != hex_string.end();) { |
| 71 | + unsigned int const c = decode_hex_char(*hex++); |
| 72 | + wkb += static_cast<char>((c << 4U) | decode_hex_char(*hex++)); |
| 73 | + } |
| 74 | + |
| 75 | + return wkb; |
| 76 | +} |
| 77 | + |
| 78 | +} // namespace util |
0 commit comments