Welcome to little lamb

Code » qmdoc » commit d1b996b

Switch output to a stralloc instead of a buffer

author Olivier Brunel
2022-12-27 13:15:02 UTC
committer Olivier Brunel
2022-12-27 16:47:34 UTC
parent d80fec679ce6885032778830585f35bd3793afc6

Switch output to a stralloc instead of a buffer

This will come in handy once we realize we don't generate the full
page output just yet, since we need to add in the TOC (which we can't
know ahead of time).

main.c +20 -14

diff --git a/main.c b/main.c
index 7433bb9..482c875 100644
--- a/main.c
+++ b/main.c
@@ -64,7 +64,7 @@ enum {
 struct ctx {
     int options;
     stralloc sa;
-    buffer out;
+    stralloc sa_out;
     struct css *css;
     struct page *pages;
     int nb_pages;
@@ -91,14 +91,19 @@ enum {
 static int
 raw_text(struct ctx *ctx, const char *text, size_t size)
 {
-    if (ctx->buf.state == BUF_OFF) {
-        if (buffer_put(&ctx->out, text, size) != size) return 0;
-        else return 1;
-    } else if (ctx->buf.state == BUF_WAITING) {
-        ctx->buf.salen = ctx->sa.len;
-        ctx->buf.state = BUF_ON;
+    stralloc *sa = &ctx->sa_out;
+
+    switch (ctx->buf.state) {
+        case BUF_WAITING:
+            ctx->buf.salen = ctx->sa.len;
+            ctx->buf.state = BUF_ON;
+            /* fall through */
+        case BUF_ON:
+            sa = &ctx->sa;
+            break;
     }
-    return stralloc_catb(&ctx->sa, text, size);
+
+    return stralloc_catb(sa, text, size);
 }
 
 #define raw_str(ctx,s)      raw_text(ctx, s, strlen(s))
@@ -837,6 +842,7 @@ main (int argc, char *argv[])
     struct ctx ctx = {
         .options = options,
         .sa = STRALLOC_ZERO,
+        .sa_out = STRALLOC_ZERO,
         .css = css,
         .pages = pages,
         .nb_pages = sizeof(pages) / sizeof(*pages),
@@ -898,19 +904,19 @@ main (int argc, char *argv[])
         int fd = openat_excl(fddest, dst);
         if (fd < 0) strerr_diefu5sys(-ERR_IO, "create '", destdir, "/", dst, "'");
 
-        char bufout[16 << 10];
-        if (!buffer_init(&ctx.out, &fd_writev, fd, bufout, sizeof(bufout)))
-            strerr_diefu5x(ERR_MISC, "init buffer for '", destdir, "/", dst, "'");
-
         ctx.cur_page = i - optind;
         int r = convert_page(&ctx);
         if (r < 0) return -r;
 
-        if (!buffer_flush(&ctx.out))
-            strerr_diefu5sys(-ERR_IO, "flush buffer to '", destdir, "/", dst, "'");
+        if (allwrite(fd, ctx.sa_out.s, ctx.sa_out.len) != ctx.sa_out.len)
+            strerr_diefu5sys(ERR_IO, "write '", destdir, "/", dst, "'");
+        ctx.sa_out.len = 0;
+        fd_close(fd);
+
         fd_close(pages[ctx.cur_page].fd);
     }
 
+    stralloc_free(&ctx.sa_out);
     stralloc_free(&ctx.sa);
 
     outse("done.");