summaryrefslogtreecommitdiff
path: root/src/common/utils.cpp
diff options
context:
space:
mode:
authorBen Longbons <b.r.longbons@gmail.com>2012-12-27 21:23:46 -0800
committerBen Longbons <b.r.longbons@gmail.com>2013-01-07 15:31:38 -0800
commitc080e504e4d74027b985b1ed675c172c083cea76 (patch)
treeac084d16d9d40c0a0c950b66eb62a0e16795d486 /src/common/utils.cpp
parentae30173d71d3bfc8514dbe70b6c90c9a3324b8fc (diff)
downloadtmwa-c080e504e4d74027b985b1ed675c172c083cea76.tar.gz
tmwa-c080e504e4d74027b985b1ed675c172c083cea76.tar.bz2
tmwa-c080e504e4d74027b985b1ed675c172c083cea76.tar.xz
tmwa-c080e504e4d74027b985b1ed675c172c083cea76.zip
Use cxxstdio
Diffstat (limited to 'src/common/utils.cpp')
-rw-r--r--src/common/utils.cpp58
1 files changed, 58 insertions, 0 deletions
diff --git a/src/common/utils.cpp b/src/common/utils.cpp
index 35fdf5a..d8c0c12 100644
--- a/src/common/utils.cpp
+++ b/src/common/utils.cpp
@@ -1,11 +1,14 @@
#include "utils.hpp"
#include <netinet/in.h>
+#include <sys/time.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
+#include <algorithm>
+
//-----------------------------------------------------
// Function to suppress control characters in a string.
//-----------------------------------------------------
@@ -95,3 +98,58 @@ const char *ip2str(struct in_addr ip, bool extra_dot)
sprintf(buf, "%d.%d.%d.%d", p[0], p[1], p[2], p[3]);
return buf;
}
+
+bool split_key_value(const std::string& line, std::string *w1, std::string *w2)
+{
+ std::string::const_iterator begin = line.begin(), end = line.end();
+
+ if (line[0] == '/' && line[1] == '/')
+ return false;
+ if (line.back() == '\r')
+ --end;
+ if (line.empty())
+ return false;
+
+ if (std::find_if(begin, end,
+ [](unsigned char c) { return c < ' '; }
+ ) != line.end())
+ return false;
+ std::string::const_iterator colon = std::find(begin, end, ':');
+ if (colon == end)
+ return false;
+ w1->assign(begin, colon);
+ ++colon;
+ while (std::isspace(*colon))
+ ++colon;
+ w2->assign(colon, end);
+ return true;
+}
+
+void stamp_time(timestamp_seconds_buffer& out, time_t *t)
+{
+ time_t when = t ? *t : time(NULL);
+ strftime(out, sizeof(out), "%Y-%m-%d %H:%M:%S", gmtime(&when));
+}
+void stamp_time(timestamp_milliseconds_buffer& out)
+{
+ struct timeval tv;
+ gettimeofday(&tv, NULL);
+ strftime(out, sizeof(out), "%Y-%m-%d %H:%M:%S", gmtime(&tv.tv_sec));
+ sprintf(out + 20, ".%03d", int(tv.tv_usec / 1000));
+}
+
+void log_with_timestamp(FILE *out, const_string line)
+{
+ if (!line)
+ {
+ fputc('\n', out);
+ return;
+ }
+ timestamp_milliseconds_buffer tmpstr;
+ stamp_time(tmpstr);
+ fwrite(tmpstr, 1, sizeof(tmpstr), out);
+ fputs(": ", out);
+ fwrite(line.data(), 1, line.size(), out);
+ if (line.back() != '\n')
+ fputc('\n', out);
+}