ucx/buffer.c

changeset 64
16590c9c497c
parent 63
1d3500806565
child 67
27e67e725d35
--- a/ucx/buffer.c	Wed Oct 10 13:58:51 2012 +0200
+++ b/ucx/buffer.c	Wed Oct 10 14:18:06 2012 +0200
@@ -87,16 +87,27 @@
 }
 
 size_t ucx_bufio(void* d, size_t s, size_t n, UcxBuffer *b, _Bool read) {
-    size_t len;
-    if (b->pos + s*n > b->size) {
-        len = b->size - b->pos;
-        if (s > 1) len -= len%s;
-    } else {
-        len = s*n;
+    size_t len = s*n;
+    if (b->pos + len > b->size) {
+        if ((b->flags & UCX_BUFFER_AUTOEXTEND) == UCX_BUFFER_AUTOEXTEND) {
+            size_t newsize = b->size;
+            while (b->pos + len > newsize) newsize <<= 1;
+            void *newspace = realloc(b->space, newsize);
+            if (newspace) {
+                memset((char*)newspace+b->size, 0, newsize-b->size);
+                b->space = newspace;
+                b->size = newsize;
+            } else {
+                len = -1;
+            }
+        } else {
+            len = b->size - b->pos;
+            if (s > 1) len -= len%s;
+        }
     }
 
-    if (len == 0) {
-        return 0;
+    if (len <= 0) {
+        return len;
     }
 
     if (read) {

mercurial