Add wpa_scnprintf() helper function
authorMoshe Benji <Moshe.Benji@intel.com>
Wed, 22 Oct 2014 12:04:02 +0000 (08:04 -0400)
committerJouni Malinen <j@w1.fi>
Sun, 16 Nov 2014 19:40:42 +0000 (21:40 +0200)
This provides a simpler version of snprintf that doesn't require further
error checks.

Signed-off-by: Moshe Benji <moshe.benji@intel.com>
Signed-off-by: Eliad Peller <eliad@wizery.com>
src/utils/common.c
src/utils/common.h

index 26c401c..64f476d 100644 (file)
@@ -183,6 +183,35 @@ void wpa_get_ntp_timestamp(u8 *buf)
        os_memcpy(buf + 4, (u8 *) &tmp, 4);
 }
 
+/**
+ * wpa_scnprintf - Simpler-to-use snprintf function
+ * @buf: Output buffer
+ * @size: Buffer size
+ * @fmt: format
+ *
+ * Simpler snprintf version that doesn't require further error checks - the
+ * return value only indicates how many bytes were actually written, excluding
+ * the NULL byte (i.e., 0 on error, size-1 if buffer is not big enough).
+ */
+int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...)
+{
+       va_list ap;
+       int ret;
+
+       if (!size)
+               return 0;
+
+       va_start(ap, fmt);
+       ret = vsnprintf(buf, size, fmt, ap);
+       va_end(ap);
+
+       if (ret < 0)
+               return 0;
+       if ((size_t) ret >= size)
+               return size - 1;
+
+       return ret;
+}
 
 static inline int _wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data,
                                    size_t len, int uppercase)
index 284e7e5..70d76a9 100644 (file)
@@ -477,6 +477,7 @@ int hex2byte(const char *hex);
 int hexstr2bin(const char *hex, u8 *buf, size_t len);
 void inc_byte_array(u8 *counter, size_t len);
 void wpa_get_ntp_timestamp(u8 *buf);
+int wpa_scnprintf(char *buf, size_t size, const char *fmt, ...);
 int wpa_snprintf_hex(char *buf, size_t buf_size, const u8 *data, size_t len);
 int wpa_snprintf_hex_uppercase(char *buf, size_t buf_size, const u8 *data,
                               size_t len);