From 0495bfb0d64bb2b318b629fd1c821dc8e2c8647d Mon Sep 17 00:00:00 2001
From: Anton Kling <anton@kling.gg>
Date: Sat, 14 Dec 2024 15:33:06 +0100
Subject: sb/printf: Add ksbprintf

Easier to add formatted strings to the string builder without
using intermediate buffers.
---
 kernel/libc/stdio/print.c | 41 +++++++++++++++++++++++------------------
 1 file changed, 23 insertions(+), 18 deletions(-)

(limited to 'kernel/libc/stdio/print.c')

diff --git a/kernel/libc/stdio/print.c b/kernel/libc/stdio/print.c
index 56b55ae..fdfd00f 100644
--- a/kernel/libc/stdio/print.c
+++ b/kernel/libc/stdio/print.c
@@ -1,5 +1,6 @@
 #include <assert.h>
 #include <kmalloc.h>
+#include <lib/sb.h>
 #include <log.h>
 #include <math.h>
 #include <stdio.h>
@@ -286,32 +287,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;
+void sb_write(struct print_context *_ctx, const char *s, int l) {
+  struct sb *ctx = (struct sb *)_ctx->data;
   assert(ctx);
-  size_t k = min(l, ctx->size);
-  memcpy(ctx->out, s, k);
-  ctx->out += k;
-  ctx->size -= k;
+  sb_append_buffer(ctx, s, l);
 }
 
-int kbnprintf(char *out, size_t size, const char *format, ...) {
+int vksbprintf(struct sb *ctx, const char *format, va_list ap) {
   struct print_context context;
 
-  struct bn_context ctx;
-  context.data = &ctx;
-  ctx.out = out;
-  ctx.size = size;
-  context.write = bn_write;
+  context.data = ctx;
+  context.write = sb_write;
 
+  return vkcprintf(&context, format, ap);
+}
+
+int ksbprintf(struct sb *ctx, const char *format, ...) {
   va_list list;
   va_start(list, format);
-  int rc = vkcprintf(&context, format, list);
+  int rc = vksbprintf(ctx, format, list);
+  va_end(list);
+  return rc;
+}
+
+int kbnprintf(char *out, size_t size, const char *format, ...) {
+  struct sb ctx;
+  sb_init_buffer(&ctx, out, size);
+
+  va_list list;
+  va_start(list, format);
+  int rc = vksbprintf(&ctx, format, list);
   va_end(list);
   return rc;
 }
-- 
cgit v1.2.3