add more struct timespec/Time formatters
[libi2ncommon] / src / timefunc.cpp
index f111763..0d2ee5d 100644 (file)
@@ -24,6 +24,7 @@ on this file might be covered by the GNU General Public License.
  *
  */
 
+#include <cstdio>
 #include <errno.h>
 #include <string>
 #include <sstream>
@@ -982,6 +983,32 @@ scan_iso8601 (const char *s,
     return tm;
 }
 
+/**
+ * @brief         Format a \c struct timespec in the schema established by
+ *                time(1): ā€œ3m14.159sā€.
+ *
+ * @param ts      The time spec to format.
+ *
+ * @return        \c boost:none in case of error during formatting, an optional
+ *                \c std::string otherwise.
+ */
+boost::optional<std::string>
+format_min_sec_msec (const struct timespec &ts)
+{
+    char ms [4] = { '\0', '\0', '\0', '\0' };
+
+    if (snprintf (ms, 4, "%0.3ld", ts.tv_nsec / 1000000) < 0) {
+        return boost::none;
+    }
+
+    const time_t min = ts.tv_sec / 60;
+    const time_t sec = ts.tv_sec - min * 60;
+
+    return I2n::to_string (min) + "m"
+         + I2n::to_string (sec) + "."
+         + ms + "s"
+         ;
+}
 
 namespace I2n {
 
@@ -1213,18 +1240,18 @@ namespace clock {
         return ::format_iso8601 (tm, date, time, tz);
     }
 
-    boost::optional<std::string>
+    std::string
     Time::make_nice_time (void) const
     {
         /* XXX the cast below results in loss of precision with 64 bit time_t! */
         return ::make_nice_time (static_cast<int> (this->value.tv_sec));
     }
 
-    boost::optional<std::string>
+    std::string
     Time::format_full_time (void) const
     { return ::format_full_time (this->value.tv_sec); }
 
-    boost::optional<std::string>
+    std::string
     Time::format_date (void) const
     { return ::format_date (this->value.tv_sec); }