代码片段收集
Get file content as string
bool GetContent(const std::string &file_name, std::string *content) {
std::ifstream fin(file_name);
if (!fin) {
return false;
}
std::stringstream str_stream;
str_stream << fin.rdbuf();
*content = str_stream.str();
return true;
}
键值对解析
// return (name,value) trimmed pair from given "name=value" string.
// return empty string on missing parts
// "key=val" => ("key", "val")
// " key = val " => ("key", "val")
// "key=" => ("key", "")
// "val" => ("", "val")
inline std::pair<std::string, std::string> extract_kv(char sep, const std::string &str)
{
auto n = str.find(sep);
std::string k, v;
if (n == std::string::npos)
{
v = str;
}
else
{
k = str.substr(0, n);
v = str.substr(n + 1);
}
return std::make_pair(trim_(k), trim_(v));
}
// return vector of key/value pairs from sequence of "K1=V1,K2=V2,.."
// "a=AAA,b=BBB,c=CCC,.." => {("a","AAA"),("b","BBB"),("c", "CCC"),...}
inline std::unordered_map<std::string, std::string> extract_key_vals(const std::string &str)
{
std::string token;
std::istringstream token_stream(str);
std::unordered_map<std::string, std::string> rv{};
while (std::getline(token_stream, token, ','))
{
if (token.empty())
{
continue;
}
auto kv = extract_kv_('=', token);
rv[kv.first] = kv.second;
}
return rv;
}
uint64_t展开
// Extracts the |i|th byte of a uint64_t, where |i == 0| extracts the least
// significant byte. It is expected that 0 <= i < 8.
static constexpr uint8_t ExtractByte(const uint64_t value, const uint32_t i) {
// DCHECK_LT(i, 8u);
return static_cast<uint8_t>((value >> (i * 8)) & 0xff);
}
static uint32_t SwapEndian(uint32_t a) {
return ((a & 0xff) << 24) | (((a >> 8) & 0xff) << 16) |
(((a >> 16) & 0xff) << 8) | ((a >> 24) & 0xff);
}
https://github.com/David-Haim/concurrencpp/blob/master/include/concurrencpp/threads/thread.h
https://github.com/google/leveldb/blob/main/include/leveldb/slice.h
https://github.com/alibaba/ilogtail/blob/main/core/common/MemoryBarrier.h