Welcome to little lamb

Code » qmdoc » commit 9048d14

Now read source file from opened fd..

author Olivier Brunel
2022-12-26 20:13:46 UTC
committer Olivier Brunel
2022-12-26 20:13:46 UTC
parent cf8ed433cee3231c377a19a4697081c2b35a942b

Now read source file from opened fd..

..file has already been seeked post header, all ready to go.

main.c +11 -34

diff --git a/main.c b/main.c
index 6f898c3..a95ae2f 100644
--- a/main.c
+++ b/main.c
@@ -590,43 +590,19 @@ text(MD_TEXTTYPE type, const MD_CHAR *text, MD_SIZE size, void *ctx_)
 }
 
 static int
-convert_file(const char *file, struct ctx *ctx)
+convert_page(struct ctx *ctx)
 {
-    int fd = open(file, O_RDONLY | O_CLOEXEC | O_NONBLOCK);
-    if (fd < 0) ret(ERR_IO, "cannot open '%s'", file);
+    size_t size = ctx->pages[ctx->cur_page].size;
+    size_t salen = ctx->sa_names.len;
 
-    struct stat st;
-    if (fstat(fd, &st) < 0) {
-        warn("cannot stat '%s'", file);
-        close(fd);
-        return ERR_IO;
-    }
+    if (!stralloc_readyplus(&ctx->sa_names, size))
+        return ERR_MEM;
 
-    size_t done = 0, len = st.st_size;
-    ssize_t sr;
-    char buf[len], *b = buf;
-
-    while (len) {
-        do { sr = read(fd, b, st.st_size); } while (sr < 0 && errno == EINTR);
-        if (sr <= 0) {
-            if (!sr) errno = 0;
-            break;
-        }
-        done += sr;
-        b += sr;
-        len -= sr;
-    }
-    if (done < len) {
-        if (!errno) errno = ENODATA;
-        warn("cannot read '%s'", file);
-        close(fd);
+    allread(ctx->pages[ctx->cur_page].fd, ctx->sa_names.s + salen, size);
+    if (errno) {
+        ctx->sa_names.len = salen;
         return ERR_IO;
     }
-    close(fd);
-
-    b = buf;
-    while (b[0] == '%' && b[1] == ' ')
-        b = strchr(b, '\n') + 1;
 
     const MD_PARSER parser = {
         .flags = MD_FLAG_COLLAPSEWHITESPACE | MD_FLAG_PERMISSIVEAUTOLINKS
@@ -637,13 +613,14 @@ convert_file(const char *file, struct ctx *ctx)
         .leave_span = leave_span,
         .text = text,
     };
-    int r = md_parse(b, done - (b - buf), &parser, ctx);
+    int r = md_parse(ctx->sa_names.s + salen, size, &parser, ctx);
     if (r < 0) {
         retx(ERR_PARSER, "parser internal error %d", -r);
     } else if (r > 0) {
         retx(-r - 100, "parser error %d", r);
     }
 
+    ctx->sa_names.len = salen;
     return 0;
 }
 
@@ -845,7 +822,7 @@ main (int argc, char *argv[])
         if (!ctx.out) strerr_diefu5sys(-ERR_IO, "open '", destdir, "/", dst, "'");
 
         ctx.cur_page = i - optind;
-        int r = convert_file(sce, &ctx);
+        int r = convert_page(&ctx);
         if (r < 0) return -r;
 
         fclose(ctx.out);