Add git__fmt as an easier to use snprintf Checking the return value of snprintf is a pain, as it must be >= 0 and < sizeof(buffer). git__fmt is a simple wrapper to perform these checks. Signed-off-by: Shawn O. Pearce <spearce@spearce.org>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
diff --git a/src/common.h b/src/common.h
index 6195078..9a827fa 100644
--- a/src/common.h
+++ b/src/common.h
@@ -19,6 +19,7 @@
#endif
#include "cc-compat.h"
+#include "git/common.h"
#include "util.h"
#include "thread-utils.h"
#include "errors.h"
diff --git a/src/util.c b/src/util.c
index feb1bd8..80829e6 100644
--- a/src/util.c
+++ b/src/util.c
@@ -1,5 +1,7 @@
#define GIT__NO_HIDE_MALLOC
#include "common.h"
+#include <stdarg.h>
+#include <stdio.h>
void *git__malloc(size_t n)
{
@@ -25,6 +27,19 @@ char *git__strdup(const char *s)
return r;
}
+int git__fmt(char *buf, size_t buf_sz, const char *fmt, ...)
+{
+ va_list va;
+ int r;
+
+ va_start(va, fmt);
+ r = vsnprintf(buf, buf_sz, fmt, va);
+ va_end(va);
+ if (r < 0 || r >= buf_sz)
+ return GIT_ERROR;
+ return r;
+}
+
int git__prefixcmp(const char *str, const char *prefix)
{
for (;;) {
diff --git a/src/util.h b/src/util.h
index 8e8169c..018fce5 100644
--- a/src/util.h
+++ b/src/util.h
@@ -26,6 +26,8 @@ extern char *git__strdup(const char *);
# define strdup(a) GIT__FORBID_MALLOC
#endif
+extern int git__fmt(char *, size_t, const char *, ...)
+ GIT_FORMAT_PRINTF(3, 4);
extern int git__prefixcmp(const char *str, const char *prefix);
extern int git__suffixcmp(const char *str, const char *suffix);