summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAnton Kling <anton@kling.gg>2024-12-10 12:23:05 +0100
committerAnton Kling <anton@kling.gg>2024-12-10 12:23:05 +0100
commitbcca3d183930eeaf3d024476f39d1d8fccf2ebab (patch)
treeaf9a4e256e569db89227026748dcba02e1fc8fa2
parent0a2e1f076786ff59bcc1fb6fdb066c0db2a5d77f (diff)
kernel: Add kbnprintf
Like snprintf but without null termination
-rw-r--r--kernel/libc/include/stdio.h1
-rw-r--r--kernel/libc/stdio/print.c41
2 files changed, 35 insertions, 7 deletions
diff --git a/kernel/libc/include/stdio.h b/kernel/libc/include/stdio.h
index 0c6a0a3..60808dd 100644
--- a/kernel/libc/include/stdio.h
+++ b/kernel/libc/include/stdio.h
@@ -8,5 +8,6 @@ void delete_characther(void);
int kprintf(const char *format, ...);
int vkprintf(const char *format, va_list list);
int ksnprintf(char *out, size_t size, const char *format, ...);
+int kbnprintf(char *out, size_t size, const char *format, ...);
#endif
diff --git a/kernel/libc/stdio/print.c b/kernel/libc/stdio/print.c
index d4ec48a..56b55ae 100644
--- a/kernel/libc/stdio/print.c
+++ b/kernel/libc/stdio/print.c
@@ -286,6 +286,36 @@ int vkcprintf(struct print_context *ctx, const char *fmt, va_list ap) {
return rc;
}
+struct bn_context {
+ char *out;
+ int size;
+};
+
+void bn_write(struct print_context *_ctx, const char *s, int l) {
+ struct bn_context *ctx = (struct bn_context *)_ctx->data;
+ assert(ctx);
+ size_t k = min(l, ctx->size);
+ memcpy(ctx->out, s, k);
+ ctx->out += k;
+ ctx->size -= k;
+}
+
+int kbnprintf(char *out, size_t size, const char *format, ...) {
+ struct print_context context;
+
+ struct bn_context ctx;
+ context.data = &ctx;
+ ctx.out = out;
+ ctx.size = size;
+ context.write = bn_write;
+
+ va_list list;
+ va_start(list, format);
+ int rc = vkcprintf(&context, format, list);
+ va_end(list);
+ return rc;
+}
+
struct sn_context {
char *out;
int size;
@@ -304,19 +334,16 @@ void sn_write(struct print_context *_ctx, const char *s, int l) {
int ksnprintf(char *out, size_t size, const char *format, ...) {
struct print_context context;
- struct sn_context *ctx = context.data = kmalloc(sizeof(struct sn_context));
- if (!ctx) {
- return -1;
- }
- ctx->out = out;
- ctx->size = size;
+ struct sn_context ctx;
+ context.data = &ctx;
+ ctx.out = out;
+ ctx.size = size;
context.write = sn_write;
va_list list;
va_start(list, format);
int rc = vkcprintf(&context, format, list);
va_end(list);
- kfree(ctx);
return rc;
}