61 lines
1.4 KiB
C++
61 lines
1.4 KiB
C++
// load environment variables from .env file
|
|
#include <fstream>
|
|
#include <cstdlib>
|
|
#include <string>
|
|
#include <cstring>
|
|
|
|
void load_env(char const* path)
|
|
{
|
|
std::ifstream f(path);
|
|
std::string line;
|
|
while (std::getline(f, line))
|
|
{
|
|
if (line.empty() || line[0] == '#')
|
|
continue;
|
|
auto pos = line.find('=');
|
|
if (pos == std::string::npos)
|
|
continue;
|
|
|
|
std::string key = line.substr(0, pos);
|
|
std::string val = line.substr(pos + 1);
|
|
|
|
#ifdef _WIN32
|
|
_putenv_s(key.c_str(), val.c_str());
|
|
#else
|
|
setenv(key.c_str(), val.c_str(), 1);
|
|
#endif
|
|
}
|
|
}
|
|
|
|
// hex to byte helper function
|
|
int hex_to_bytes_upper(const char *hex, unsigned char *out, size_t out_size)
|
|
{
|
|
size_t i = 0;
|
|
while (hex[0] && hex[1])
|
|
{
|
|
if (i >= out_size)
|
|
return -1;
|
|
unsigned char h = hex[0];
|
|
unsigned char l = hex[1];
|
|
int hi = (h <= '9') ? (h - '0') : (h - 'A' + 10);
|
|
int lo = (l <= '9') ? (l - '0') : (l - 'A' + 10);
|
|
// minimal sanity check
|
|
if (hi < 0 || hi > 15 || lo < 0 || lo > 15)
|
|
return -1;
|
|
out[i++] = (unsigned char)((hi << 4) | lo);
|
|
hex += 2;
|
|
}
|
|
return (int)i;
|
|
}
|
|
|
|
char * byte_to_hex(unsigned char *bytes, size_t len)
|
|
{
|
|
char *hex = new char[len * 2 + 1];
|
|
for (size_t i = 0; i < len; i++)
|
|
{
|
|
sprintf(hex + i * 2, "%02X", bytes[i]);
|
|
}
|
|
hex[len * 2] = '\0';
|
|
return hex;
|
|
}
|