Program Listing for File util.hpp

Return to documentation for file (util.hpp)

#ifndef UTIL_H_
#define UTIL_H_

#include <climits>
#include <string>
#include <vector>
#include <unistd.h>
#include <iostream>
#include <chrono>
#include <iomanip>
#include <sstream>

namespace Util {

inline std::vector<std::string> split(const std::string &text, char sep) {
    std::vector<std::string> tokens;
    std::size_t start = 0, end = 0;
    while ((end = text.find(sep, start)) != std::string::npos) {
        tokens.push_back(text.substr(start, end - start));
        start = end + 1;
    }
    tokens.push_back(text.substr(start));
    return tokens;
}


inline std::string get_full_hostname() {
    char hostname[HOST_NAME_MAX];
    int rc = ::gethostname(hostname, HOST_NAME_MAX);
    return std::string(rc < 0 ? "" : hostname);
}


inline std::string get_hostname() {
    return split(get_full_hostname(), '.')[0];
}


inline std::string ISO8601TimeUTC() {
    auto now = std::chrono::system_clock::now();
    auto itt = std::chrono::system_clock::to_time_t(now);
    std::ostringstream ss;
    ss << std::put_time(gmtime(&itt), "%FT%TZ");
    return ss.str();
}

} // namespace Util

#endif /* UTIL_H_ */