From c3658558df681378b98faa04397dc3e5c247e159 Mon Sep 17 00:00:00 2001 From: WormHeamer Date: Mon, 29 Dec 2025 06:14:59 -0500 Subject: add txt_collect_range() and txt_read_chunk() --- txt.c | 38 +++++++++++++++++++++++++++++++++++--- txt.h | 5 ++++- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/txt.c b/txt.c index 054245d..038140d 100644 --- a/txt.c +++ b/txt.c @@ -7,9 +7,11 @@ #include #include "wrmr.h" +#include "arena.h" #include "dynarr.h" #include "txt.h" #include "utf8.h" +#include "str.h" void txt_replace_piece(Txt *b, u32 pi, TxtBufIdx buf, u32 ofs, u32 n) { b->ptbl.v[pi] = (TxtPiece) { buf, ofs, n }; @@ -277,18 +279,48 @@ void txt_free(Txt *t) { free(t->ptbl.v); } -void txt_write_range(int fd, TxtLoc lo, TxtLoc hi) { +Str txt_collect_range(TxtLoc lo, TxtLoc hi, Arena *a) { + DYNARR(char) buf = { 0 }; while (lo.p < hi.p) { TxtPiece *p = &lo.t->ptbl.v[lo.p]; - write(fd, lo.t->buf[p->buf].s + p->ofs + lo.i, p->n - lo.i); + DA_APUSH_MULT(&buf, a, lo.t->buf[p->buf].s + p->ofs + lo.i, p->n - lo.i); lo.p++; lo.i = 0; } ASSERT(lo.p == hi.p); if (hi.i > lo.i) { TxtPiece *p = &lo.t->ptbl.v[lo.p]; - write(fd, lo.t->buf[p->buf].s + p->ofs + lo.i, hi.i - lo.i); + DA_AGROW(&buf, a, hi.i - lo.i); + memcpy((&buf)->v + (&buf)->n, lo.t->buf[p->buf].s + p->ofs + lo.i, DA_ELEM(&buf, hi.i - lo.i)); + (&buf)->n += (hi.i - lo.i); + //DA_APUSH_MULT(&buf, a, lo.t->buf[p->buf].s + p->ofs + lo.i, hi.i - lo.i); } + return (Str) { buf.v, buf.n }; +} + +u32 txt_read_chunk(TxtLoc *lo, TxtLoc hi, char *buf, u32 sz) { + u32 n = 0; + TxtLoc l = *lo; + while (n < sz && l.p < hi.p) { + TxtPiece *p = &l.t->ptbl.v[l.p]; + u32 copy_n = p->n - l.i; + if (copy_n > sz - n) copy_n = sz - n; + memcpy(buf + n, l.t->buf[p->buf].s + p->ofs + l.i, copy_n); + n += copy_n; + l.i += copy_n; + if (l.i >= p->n) { + l.p++; + l.i = 0; + } + } + if (n < sz && hi.i > l.i) { + TxtPiece *p = &l.t->ptbl.v[l.p]; + u32 copy_n = hi.i - l.i; + if (copy_n > sz - n) copy_n = sz - n; + memcpy(buf + n, l.t->buf[p->buf].s + p->ofs + l.i, copy_n); + } + *lo = l; + return n; } /* navigation */ diff --git a/txt.h b/txt.h index a7dd908..3b62e04 100644 --- a/txt.h +++ b/txt.h @@ -2,6 +2,8 @@ #define TXT_H #include "dynarr.h" +#include "arena.h" +#include "str.h" typedef enum : u8 { TXT_SRC, @@ -39,7 +41,8 @@ int txt_load(Txt *b, const char *path); int txt_save(Txt *b, const char *path); void txt_free(Txt *b); -void txt_write_range(int fd, TxtLoc lo, TxtLoc hi); +Str txt_collect_range(TxtLoc lo, TxtLoc hi, Arena *a); +u32 txt_read_chunk(TxtLoc *lo, TxtLoc hi, char *buf, u32 sz); /* insertion & deletion */ -- cgit v1.2.3