* changed. (Bytes in the buffer might be smashed, but the buffer
* position does not change, and the NUL marker stays in place at the
* current buffer position.)
+ * - If '(*ppbuf - pend) <= 0' (or ppbuf is NULL), fail with EINVAL.
*/
int
xvsbprintf(
{
char *pbuf = (ppbuf) ? *ppbuf : NULL;
int rc = -1;
- if (pbuf) {
- size_t ilen = (size_t)(pend - pbuf);
- if (ilen) {
- *pbuf = '\0';
- rc = vsnprintf(pbuf, ilen, pfmt, va);
- if (rc > 0) {
- if ((size_t)rc >= ilen)
- rc = 0;
- pbuf += rc;
- }
- *pbuf = '\0'; /* fear of bad vsnprintf */
- }
+ if (pbuf && (pend - pbuf > 0)) {
+ size_t blen = (size_t)(pend - pbuf);
+ rc = vsnprintf(pbuf, blen, pfmt, va);
+ if (rc > 0) {
+ if ((size_t)rc >= blen)
+ rc = 0;
+ pbuf += rc;
+ }
+ *pbuf = '\0'; /* fear of bad vsnprintf */
*ppbuf = pbuf;
} else {
errno = EINVAL;
return rc;
}
-/* variadic wrapper around the buufer string formatter */
+/* variadic wrapper around the buffer string formatter */
int
xsbprintf(
char **ppbuf, /* pointer to buffer pointer (I/O) */
extern void tearDown(void);
extern void test_NullBuf1(void);
extern void test_NullBuf2(void);
+extern void test_EndBeyond(void);
extern void test_SmallBuf(void);
extern void test_MatchBuf(void);
extern void test_BigBuf(void);
extern void test_SimpleArgs(void);
+extern void test_Increment1(void);
//=======Suite Setup=====
UnityBegin("sbprintf.c");
RUN_TEST(test_NullBuf1, 7);
RUN_TEST(test_NullBuf2, 14);
- RUN_TEST(test_SmallBuf, 23);
- RUN_TEST(test_MatchBuf, 34);
- RUN_TEST(test_BigBuf, 45);
- RUN_TEST(test_SimpleArgs, 56);
+ RUN_TEST(test_EndBeyond, 23);
+ RUN_TEST(test_SmallBuf, 33);
+ RUN_TEST(test_MatchBuf, 44);
+ RUN_TEST(test_BigBuf, 55);
+ RUN_TEST(test_SimpleArgs, 66);
+ RUN_TEST(test_Increment1, 78);
return (UnityEnd());
}
TEST_ASSERT_EQUAL_PTR(bp, NULL);
}
+extern void test_EndBeyond(void);
+void test_EndBeyond(void)
+{
+ char ba[2];
+ char *bp = ba + 1;
+ char *ep = ba;
+ int rc = xsbprintf(&bp, ep, "blah");
+ TEST_ASSERT(rc == -1 && errno == EINVAL);
+}
+
extern void test_SmallBuf(void);
void test_SmallBuf(void)
{
TEST_ASSERT_FALSE(strcmp(ba, "1234"));
}
+extern void test_Increment1(void);
+void test_Increment1(void)
+{
+ char ba[10];
+ char *bp = ba;
+ char *ep = ba + sizeof(ba);
+ int rc;
+
+ rc = xsbprintf(&bp, ep, "%d%d%d%d", 1, 2, 3, 4);
+ TEST_ASSERT(rc == 4 && strlen(ba) == 4);
+ TEST_ASSERT_EQUAL_PTR(bp, ba + 4);
+
+ rc = xsbprintf(&bp, ep, "%s", "frob");
+ TEST_ASSERT(rc == 4 && strlen(ba) == 8);
+ TEST_ASSERT_EQUAL_PTR(bp, ba + 8);
+ TEST_ASSERT_FALSE(strcmp(ba, "1234frob"));
+}
+