New functions ds_put_strftime(), ds_chomp().
authorBen Pfaff <blp@nicira.com>
Tue, 19 Aug 2008 20:57:55 +0000 (13:57 -0700)
committerBen Pfaff <blp@nicira.com>
Tue, 26 Aug 2008 20:25:17 +0000 (13:25 -0700)
include/compiler.h
include/dynamic-string.h
lib/dynamic-string.c

index d3ea6171973715d1e7239072419fd8c175f99ed0..2e185bfa81701536ade2b4366f2c6124da8a60b7 100644 (file)
@@ -38,6 +38,7 @@
 #define UNUSED __attribute__((__unused__))
 #define PACKED __attribute__((__packed__))
 #define PRINTF_FORMAT(FMT, ARG1) __attribute__((__format__(printf, FMT, ARG1)))
+#define STRFTIME_FORMAT(FMT) __attribute__((__format__(__strftime__, FMT, 0)))
 #define likely(x) __builtin_expect((x),1)
 #define unlikely(x) __builtin_expect((x),0)
 
index 7c1b04668eab4c501bc06594a1835f4962116a82..7a25b07057a9fa8eed72a1310867176de513a8d3 100644 (file)
@@ -40,6 +40,8 @@
 #include <stdint.h>
 #include "compiler.h"
 
+struct tm;
+
 struct ds {
     char *string;       /* Null-terminated string. */
     size_t length;      /* Bytes used, not including null terminator. */
@@ -58,11 +60,14 @@ void ds_put_format(struct ds *, const char *, ...) PRINTF_FORMAT(2, 3);
 void ds_put_format_valist(struct ds *, const char *, va_list)
     PRINTF_FORMAT(2, 0);
 void ds_put_printable(struct ds *, const char *, size_t);
+void ds_put_strftime(struct ds *, const char *, const struct tm *)
+    STRFTIME_FORMAT(2);
 void ds_put_hex_dump(struct ds *ds, const void *buf_, size_t size,
                      uintptr_t ofs, bool ascii);
 char *ds_cstr(struct ds *);
 void ds_destroy(struct ds *);
 
 int ds_last(const struct ds *);
+void ds_chomp(struct ds *, int c);
 
 #endif /* dynamic-string.h */
index 4b836819fa224c5dfe85dd5a55d453b77a6fdf8f..3193d438f03d6cc7add8a0490c63ffd5265e605d 100644 (file)
@@ -36,6 +36,7 @@
 #include <assert.h>
 #include <stdlib.h>
 #include <string.h>
+#include <time.h>
 #include "util.h"
 
 void
@@ -141,6 +142,20 @@ ds_put_printable(struct ds *ds, const char *s, size_t n)
     }
 }
 
+void
+ds_put_strftime(struct ds *ds, const char *template, const struct tm *tm)
+{
+    for (;;) {
+        size_t avail = ds->string ? ds->allocated - ds->length + 1 : 0;
+        size_t used = strftime(&ds->string[ds->length], avail, template, tm);
+        if (used) {
+            ds->length += used;
+            return;
+        }
+        ds_reserve(ds, ds->length + (avail < 32 ? 64 : 2 * avail)); 
+    }
+}
+
 char *
 ds_cstr(struct ds *ds)
 {
@@ -215,3 +230,11 @@ ds_last(const struct ds *ds)
 {
     return ds->length > 0 ? (unsigned char) ds->string[ds->length - 1] : EOF;
 }
+
+void
+ds_chomp(struct ds *ds, int c)
+{
+    if (ds->length > 0 && ds->string[ds->length - 1] == (char) c) {
+        ds->string[--ds->length] = '\0';
+    }
+}