summary | shortlog | log | commit | commitdiff | tree
raw | patch | inline | side by side (parent: 7224f5d)
raw | patch | inline | side by side (parent: 7224f5d)
author | Florian Forster <octo@collectd.org> | |
Sun, 12 May 2013 10:17:47 +0000 (12:17 +0200) | ||
committer | Florian Forster <octo@collectd.org> | |
Sun, 12 May 2013 10:17:47 +0000 (12:17 +0200) |
src/common.c | patch | blob | history | |
src/common.h | patch | blob | history |
diff --git a/src/common.c b/src/common.c
index 79e4c02c631841334307222430e02d4bc381153d..d963efa556a6f60ce6f71c3472f90e791dc48c4e 100644 (file)
--- a/src/common.c
+++ b/src/common.c
return (ret);
} /* int ssnprintf */
+char *ssnprintf_alloc (char const *format, ...) /* {{{ */
+{
+ char static_buffer[1024] = "";
+ char *alloc_buffer;
+ size_t alloc_buffer_size;
+ int status;
+ va_list ap;
+
+ /* Try printing into the static buffer. In many cases it will be
+ * sufficiently large and we can simply return a strdup() of this
+ * buffer. */
+ va_start (ap, format);
+ status = vsnprintf (static_buffer, sizeof (static_buffer), format, ap);
+ va_end (ap);
+ if (status < 0)
+ return (NULL);
+
+ /* "status" does not include the null byte. */
+ alloc_buffer_size = (size_t) (status + 1);
+ if (alloc_buffer_size <= sizeof (static_buffer))
+ return (strdup (static_buffer));
+
+ /* Allocate a buffer large enough to hold the string. */
+ alloc_buffer = malloc (alloc_buffer_size);
+ if (alloc_buffer == NULL)
+ return (NULL);
+ memset (alloc_buffer, 0, alloc_buffer_size);
+
+ /* Print again into this new buffer. */
+ va_start (ap, format);
+ status = vsnprintf (alloc_buffer, alloc_buffer_size, format, ap);
+ va_end (ap);
+ if (status < 0)
+ {
+ sfree (alloc_buffer);
+ return (NULL);
+ }
+
+ return (alloc_buffer);
+} /* }}} char *ssnprintf_alloc */
+
char *sstrdup (const char *s)
{
char *r;
diff --git a/src/common.h b/src/common.h
index 7c0d9369cf498db70712958a6d593ccb0d58d3e8..317be8d1579d063cc23338e229abcdede533da84 100644 (file)
--- a/src/common.h
+++ b/src/common.h
typedef struct rate_to_value_state_s rate_to_value_state_t;
char *sstrncpy (char *dest, const char *src, size_t n);
+
+__attribute__ ((format(printf,3,4)))
int ssnprintf (char *dest, size_t n, const char *format, ...);
+
+__attribute__ ((format(printf,1,2)))
+char *ssnprintf_alloc (char const *format, ...);
+
char *sstrdup(const char *s);
void *smalloc(size_t size);
char *sstrerror (int errnum, char *buf, size_t buflen);