summaryrefslogtreecommitdiffstats
path: root/libc-top-half/musl/src/stdio/vsnprintf.c
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 13:54:38 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-17 13:54:38 +0000
commit8c1ab65c0f548d20b7f177bdb736daaf603340e1 (patch)
treedf55b7e75bf43f2bf500845b105afe3ac3a5157e /libc-top-half/musl/src/stdio/vsnprintf.c
parentInitial commit. (diff)
downloadwasi-libc-8c1ab65c0f548d20b7f177bdb736daaf603340e1.tar.xz
wasi-libc-8c1ab65c0f548d20b7f177bdb736daaf603340e1.zip
Adding upstream version 0.0~git20221206.8b7148f.upstream/0.0_git20221206.8b7148f
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'libc-top-half/musl/src/stdio/vsnprintf.c')
-rw-r--r--libc-top-half/musl/src/stdio/vsnprintf.c57
1 files changed, 57 insertions, 0 deletions
diff --git a/libc-top-half/musl/src/stdio/vsnprintf.c b/libc-top-half/musl/src/stdio/vsnprintf.c
new file mode 100644
index 0000000..08989d6
--- /dev/null
+++ b/libc-top-half/musl/src/stdio/vsnprintf.c
@@ -0,0 +1,57 @@
+#include "stdio_impl.h"
+#include <limits.h>
+#include <string.h>
+#include <errno.h>
+#include <stdint.h>
+
+struct cookie {
+ char *s;
+ size_t n;
+};
+
+#define MIN(a, b) ((a) < (b) ? (a) : (b))
+
+static size_t sn_write(FILE *f, const unsigned char *s, size_t l)
+{
+ struct cookie *c = f->cookie;
+ size_t k = MIN(c->n, f->wpos - f->wbase);
+ if (k) {
+ memcpy(c->s, f->wbase, k);
+ c->s += k;
+ c->n -= k;
+ }
+ k = MIN(c->n, l);
+ if (k) {
+ memcpy(c->s, s, k);
+ c->s += k;
+ c->n -= k;
+ }
+ *c->s = 0;
+ f->wpos = f->wbase = f->buf;
+ /* pretend to succeed, even if we discarded extra data */
+ return l;
+}
+
+int vsnprintf(char *restrict s, size_t n, const char *restrict fmt, va_list ap)
+{
+ unsigned char buf[1];
+ char dummy[1];
+ struct cookie c = { .s = n ? s : dummy, .n = n ? n-1 : 0 };
+ FILE f = {
+ .lbf = EOF,
+ .write = sn_write,
+#if defined(__wasilibc_unmodified_upstream) || defined(_REENTRANT)
+ .lock = -1,
+#endif
+ .buf = buf,
+ .cookie = &c,
+ };
+
+ if (n > INT_MAX) {
+ errno = EOVERFLOW;
+ return -1;
+ }
+
+ *c.s = 0;
+ return vfprintf(&f, fmt, ap);
+}