Use TR_LIST for TR_FILTER's 'flines' member
[trust_router.git] / common / tr_util.c
index 06b7d8a..ef85776 100644 (file)
 #include <assert.h>
 #include <stdio.h>
 #include <string.h>
-#include <tr_dh.h>
+#include <time.h>
+#include <tr_util.h>
+#include <stdlib.h>
 
 void tr_bin_to_hex(const unsigned char * bin, size_t bin_len,
                   char * hex_out, size_t hex_len)
 {
   assert(hex_len >= 2*bin_len);
   while (bin_len >0) {
-    snprintf(hex_out, hex_len, "%2x", bin[0]);
+    snprintf(hex_out, hex_len, "%.2x", bin[0]);
     bin++, hex_out += 2;
     bin_len--;
     hex_len -= 2;
   }
 }
+
+/* Returns 0 if ts1==ts2, <0 if ts1<ts2, >= if ts1>ts2.
+ * Assumes that tv_nsec <= 1e9. */
+int tr_cmp_timespec(struct timespec *ts1, struct timespec *ts2)
+{
+  if (ts1->tv_sec > ts2->tv_sec)
+    return 1;
+
+  if (ts1->tv_sec < ts2->tv_sec)
+    return -1;
+
+  /* ts1->tv_sec==ts2->tv_sec */
+
+  if (ts1->tv_nsec > ts2->tv_nsec)
+    return 1;
+
+  if (ts1->tv_nsec < ts2->tv_nsec)
+    return -1;
+
+  return 0;
+}
+
+/**
+ * Convert a struct timespec to a string representation
+ * @param ts
+ * @return
+ */
+char *timespec_to_str(struct timespec *ts)
+{
+  struct tm tm;
+  char *s=NULL;
+
+  if (localtime_r(&(ts->tv_sec), &tm)==NULL)
+    return NULL;
+
+  s=malloc(40); /* long enough to contain strftime result */
+  if (s==NULL)
+    return NULL;
+
+  if (strftime(s, 40, "%F %T", &tm)==0) {
+    free(s);
+    return NULL;
+  }
+  return s;
+}
+