Commit 9132836bd2bdbe7f92205bc82d3975a4d047e909

Baptiste 2024-07-25T19:30:02

buf_read_until* functions

diff --git a/libkc3/buf.c b/libkc3/buf.c
index 63a09db..01071b4 100644
--- a/libkc3/buf.c
+++ b/libkc3/buf.c
@@ -791,6 +791,80 @@ sw buf_read_u64 (s_buf *buf, u64 *p)
   return r;
 }
 
+s_str * buf_read_until_1_into_str(s_buf *buf, const char *end, s_str *dest)
+{
+  character c;
+  sw r;
+  s_buf_save save;
+  s_buf tmp;
+  buf_save_init(buf, &save);
+  while (1) {
+    if ((r = buf_read_1(buf, end)) < 0)
+      goto restore;
+    if (r) {
+      buf_init(&tmp, false, buf->size, buf->ptr.pchar);
+      tmp.rpos = save.rpos;
+      tmp.wpos = buf->rpos;
+      if (! buf_read_to_str(&tmp, dest))
+        goto restore;
+      return dest;
+    }
+    if ((r = buf_read_character_utf8(buf, &c)) <= 0)
+      goto restore;
+  }
+ restore:
+  buf_save_restore_rpos(buf, &save);
+  buf_save_clean(buf, &save);
+  return NULL;
+}
+
+sw buf_read_until_character_into_str (s_buf *buf, character end, s_str *dest)
+{
+  s_str end_str;
+  sw r;
+  s_str tmp;
+  if (! str_init_character(&end_str, end))
+    return -1;
+  if ((r = buf_read_until_str_into_str(buf, &end_str, &tmp)) > 0)
+    *dest = tmp;
+  str_clean(&end_str);
+  return r;
+}
+
+sw buf_read_until_str_into_str (s_buf *buf, const s_str *end, s_str *dest)
+{
+  character c;
+  sw r;
+  sw result = 0;
+  s_buf_save save;
+  s_buf tmp;
+  buf_save_init(buf, &save);
+  while (1) {
+    if ((r = buf_read_str(buf, end)) < 0)
+      goto restore;
+    if (r) {
+      result += r;
+      buf_init(&tmp, false, buf->size, buf->ptr.pchar);
+      tmp.rpos = save.rpos;
+      tmp.wpos = buf->rpos;
+      if (! buf_read_to_str(&tmp, dest)) {
+        r = -1;
+        goto restore;
+      }
+      r = result;
+      goto clean;
+    }
+    if ((r = buf_read_character_utf8(buf, &c)) <= 0)
+      goto restore;
+    result += r;
+  }
+ restore:
+  buf_save_restore_rpos(buf, &save);
+ clean:
+  buf_save_clean(buf, &save);
+  return r;
+}
+
 sw buf_refill (s_buf *buf, sw size)
 {
   sw r = buf->wpos - buf->rpos;
diff --git a/libkc3/buf.h b/libkc3/buf.h
index 90a0e05..0d1519a 100644
--- a/libkc3/buf.h
+++ b/libkc3/buf.h
@@ -80,6 +80,12 @@ sw      buf_read_u8 (s_buf *buf, u8 *p);
 sw      buf_read_u16 (s_buf *buf, u16 *p);
 sw      buf_read_u32 (s_buf *buf, u32 *p);
 sw      buf_read_u64 (s_buf *buf, u64 *p);
+s_str * buf_read_until_1_into_str(s_buf *buf, const char *end,
+                                  s_str *dest);
+sw      buf_read_until_character_into_str (s_buf *buf, character end,
+                                           s_str *dest);
+sw      buf_read_until_str_into_str (s_buf *buf, const s_str *end,
+                                     s_str *dest);
 sw      buf_read_integer (s_buf *buf, s_integer *dst);
 sw      buf_refill (s_buf *buf, sw size);
 sw      buf_refill_compact (s_buf *buf);