Ring Daemon 16.0.0
Loading...
Searching...
No Matches
CommonData.cpp
Go to the documentation of this file.
1/*
2 This file is part of cpp-ethereum.
3
4 cpp-ethereum is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 3 of the License, or
7 (at your option) any later version.
8
9 cpp-ethereum is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
16*/
22#include "CommonData.h"
23
24#include <stdexcept>
25
26using namespace std;
27using namespace dev;
28
29namespace {
30int
31fromHexChar(char _i) noexcept
32{
33 if (_i >= '0' && _i <= '9')
34 return _i - '0';
35 if (_i >= 'a' && _i <= 'f')
36 return _i - 'a' + 10;
37 if (_i >= 'A' && _i <= 'F')
38 return _i - 'A' + 10;
39 return -1;
40}
41} // namespace
42
43bool
44dev::isHex(string const& _s) noexcept
45{
46 auto it = _s.begin();
47 if (_s.compare(0, 2, "0x") == 0)
48 it += 2;
49 return std::all_of(it, _s.end(), [](char c) { return fromHexChar(c) != -1; });
50}
51
53dev::fromHex(std::string const& _s, WhenError _throw)
54{
55 unsigned s = (_s.size() >= 2 && _s[0] == '0' && _s[1] == 'x') ? 2 : 0;
56 std::vector<uint8_t> ret;
57 ret.reserve((_s.size() - s + 1) / 2);
58
59 if (_s.size() % 2) {
60 int h = fromHexChar(_s[s++]);
61 if (h != -1)
62 ret.push_back(h);
63 else if (_throw == WhenError::Throw)
64 throw std::runtime_error("BadHexCharacter");
65 else
66 return bytes();
67 }
68 for (unsigned i = s; i < _s.size(); i += 2) {
69 int h = fromHexChar(_s[i]);
70 int l = fromHexChar(_s[i + 1]);
71 if (h != -1 && l != -1)
72 ret.push_back((uint8_t)(h * 16 + l));
73 else if (_throw == WhenError::Throw)
74 throw std::runtime_error("BadHexCharacter");
75 else
76 return bytes();
77 }
78 return ret;
79}
80
83{
84 std::vector<uint8_t> ret;
85 ret.reserve(_s.size() * 2);
86 for (auto i : _s) {
87 ret.push_back(i / 16);
88 ret.push_back(i % 16);
89 }
90 return ret;
91}
A modifiable reference to an existing object or vector in memory.
Definition vector_ref.h:21
size_t size() const
Definition vector_ref.h:97
Definition Address.h:25
bool isHex(std::string const &_s) noexcept
bytes asNibbles(bytesConstRef const &_s)
std::vector< uint8_t > bytes
bytes fromHex(std::string const &_s, WhenError _throw=WhenError::DontThrow)
WhenError
Definition CommonData.h:38