Line data Source code
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 : */ 17 : /** @file CommonData.cpp 18 : * @author Gav Wood <i@gavwood.com> 19 : * @date 2014 20 : */ 21 : 22 : #include "CommonData.h" 23 : 24 : #include <stdexcept> 25 : 26 : using namespace std; 27 : using namespace dev; 28 : 29 : namespace { 30 : int 31 0 : fromHexChar(char _i) noexcept 32 : { 33 0 : if (_i >= '0' && _i <= '9') 34 0 : return _i - '0'; 35 0 : if (_i >= 'a' && _i <= 'f') 36 0 : return _i - 'a' + 10; 37 0 : if (_i >= 'A' && _i <= 'F') 38 0 : return _i - 'A' + 10; 39 0 : return -1; 40 : } 41 : } // namespace 42 : 43 : bool 44 0 : dev::isHex(string const& _s) noexcept 45 : { 46 0 : auto it = _s.begin(); 47 0 : if (_s.compare(0, 2, "0x") == 0) 48 0 : it += 2; 49 0 : return std::all_of(it, _s.end(), [](char c) { return fromHexChar(c) != -1; }); 50 : } 51 : 52 : bytes 53 0 : dev::fromHex(std::string const& _s, WhenError _throw) 54 : { 55 0 : unsigned s = (_s.size() >= 2 && _s[0] == '0' && _s[1] == 'x') ? 2 : 0; 56 0 : std::vector<uint8_t> ret; 57 0 : ret.reserve((_s.size() - s + 1) / 2); 58 : 59 0 : if (_s.size() % 2) { 60 0 : int h = fromHexChar(_s[s++]); 61 0 : if (h != -1) 62 0 : ret.push_back(h); 63 0 : else if (_throw == WhenError::Throw) 64 0 : throw std::runtime_error("BadHexCharacter"); 65 : else 66 0 : return bytes(); 67 : } 68 0 : for (unsigned i = s; i < _s.size(); i += 2) { 69 0 : int h = fromHexChar(_s[i]); 70 0 : int l = fromHexChar(_s[i + 1]); 71 0 : if (h != -1 && l != -1) 72 0 : ret.push_back((uint8_t)(h * 16 + l)); 73 0 : else if (_throw == WhenError::Throw) 74 0 : throw std::runtime_error("BadHexCharacter"); 75 : else 76 0 : return bytes(); 77 : } 78 0 : return ret; 79 0 : } 80 : 81 : bytes 82 0 : dev::asNibbles(bytesConstRef const& _s) 83 : { 84 0 : std::vector<uint8_t> ret; 85 0 : ret.reserve(_s.size() * 2); 86 0 : for (auto i : _s) { 87 0 : ret.push_back(i / 16); 88 0 : ret.push_back(i % 16); 89 : } 90 0 : return ret; 91 0 : }