-
Notifications
You must be signed in to change notification settings - Fork 1
/
misc.cpp
114 lines (82 loc) · 1.82 KB
/
misc.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <boost/algorithm/string/replace.hpp>
#include <boost/lexical_cast.hpp>
#include <cstdint>
#include <fstream>
#include <iomanip>
#include <sstream>
#include <string>
#include <vector>
#include <misc.hpp>
using namespace std;
namespace eth_interface
{
// https://stackoverflow.com/questions/116038/how-do-i-read-an-entire-file-into-a-stdstring-in-c
string
readFile2(string const& fileName)
{
ifstream ifs(fileName.c_str(), ios::in | ios::binary | ios::ate);
ifstream::pos_type fileSize = ifs.tellg();
ifs.seekg(0, ios::beg);
vector<char> bytes(fileSize);
ifs.read(bytes.data(), fileSize);
return string(bytes.data(), fileSize);
}
bool
isHex(string const& str)
{
for (char* s = (char*)str.c_str(); *s != 0; s++)
{
if ((*s < 48) || (*s > 70 && *s < 97) || (*s > 102))
return false;
}
return true;
}
bool
isEthereumAddress(string const& str)
{
return isHex(str) && str.length() > 0 && str.length() <= 40;
}
string
escapeSingleQuotes(string const& str)
{
return boost::replace_all_copy(str, "'", "'\\''");
}
// https://stackoverflow.com/questions/17261798/converting-a-hex-string-to-a-byte-array
vector<char>
hexToBytes(string const& hex)
{
vector<char> bytes;
for (unsigned int i = 0; i < hex.length(); i += 2)
{
string byteString = hex.substr(i, 2);
char byte = (char)strtol(byteString.c_str(), NULL, 16);
bytes.push_back(byte);
}
return bytes;
}
// https://stackoverflow.com/questions/14050452/how-to-convert-byte-array-to-hex-string-in-visual-c#14051107
string
hexStr(unsigned char* data, uint16_t len)
{
std::stringstream ss;
ss << std::hex;
for (int i(0); i < len; ++i)
{
ss << std::setw(2) << std::setfill('0') << (int)data[i];
}
return ss.str();
}
bool
isInt(string& s)
{
try
{
boost::lexical_cast<uint64_t>(s);
}
catch (...)
{
return false;
}
return true;
}
} //namespace