|
| 1 | +/** |
| 2 | + * Copyright (c) 2011-2025 libbitcoin developers (see AUTHORS) |
| 3 | + * |
| 4 | + * This file is part of libbitcoin. |
| 5 | + * |
| 6 | + * This program is free software: you can redistribute it and/or modify |
| 7 | + * it under the terms of the GNU Affero General Public License as published by |
| 8 | + * the Free Software Foundation, either version 3 of the License, or |
| 9 | + * (at your option) any later version. |
| 10 | + * |
| 11 | + * This program is distributed in the hope that it will be useful, |
| 12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 | + * GNU Affero General Public License for more details. |
| 15 | + * |
| 16 | + * You should have received a copy of the GNU Affero General Public License |
| 17 | + * along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 | + */ |
| 19 | +#ifndef LIBBITCOIN_SYSTEM_STREAM_STREAMERS_BASE16_READER_IPP |
| 20 | +#define LIBBITCOIN_SYSTEM_STREAM_STREAMERS_BASE16_READER_IPP |
| 21 | + |
| 22 | +#include <bitcoin/system/define.hpp> |
| 23 | +#include <bitcoin/system/radix/radix.hpp> |
| 24 | +#include <bitcoin/system/stream/streamers/byte_reader.hpp> |
| 25 | + |
| 26 | +namespace libbitcoin { |
| 27 | +namespace system { |
| 28 | + |
| 29 | +// constructors |
| 30 | +// ---------------------------------------------------------------------------- |
| 31 | + |
| 32 | +template <typename IStream> |
| 33 | +hex_reader<IStream>::hex_reader(IStream& source) NOEXCEPT |
| 34 | + : base(source) |
| 35 | +{ |
| 36 | +} |
| 37 | + |
| 38 | +template <typename IStream> |
| 39 | +hex_reader<IStream>::hex_reader(IStream& source, |
| 40 | + const base::memory_arena& arena) NOEXCEPT |
| 41 | + : base(source, arena) |
| 42 | +{ |
| 43 | +} |
| 44 | + |
| 45 | +// protected |
| 46 | +// ---------------------------------------------------------------------------- |
| 47 | + |
| 48 | +template <typename IStream> |
| 49 | +void hex_reader<IStream>::do_read_bytes(uint8_t* buffer, |
| 50 | + size_t size) NOEXCEPT |
| 51 | +{ |
| 52 | + if (!is_even(size)) |
| 53 | + { |
| 54 | + this->invalidate(); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + char chars[two]; |
| 59 | + const auto bytes = pointer_cast<uint8_t>(&chars[zero]); |
| 60 | + |
| 61 | + // Iteration avoids writing to dynamically-allocated buffer of size. |
| 62 | + for (auto octet = buffer; octet < std::next(buffer, size); ++octet) |
| 63 | + { |
| 64 | + base::do_read_bytes(bytes, two); |
| 65 | + if (!is_base16(chars[0]) || !is_base16(chars[1])) |
| 66 | + { |
| 67 | + this->invalidate(); |
| 68 | + return; |
| 69 | + } |
| 70 | + |
| 71 | + *octet = from_base16_characters(chars[0], chars[1]); |
| 72 | + } |
| 73 | +} |
| 74 | + |
| 75 | +} // namespace system |
| 76 | +} // namespace libbitcoin |
| 77 | + |
| 78 | +#endif |
0 commit comments