ref: bcc3d3e54ac5538e30c01b4407b987ac4e4c0b13
parent: 811e638d4f0ae4c79b5871ec08695963e6710a7a
author: Sigrid Solveig Haflínudóttir <sigrid@ftrv.se>
date: Mon Mar 27 11:18:16 EDT 2023
import "stop over-allocating ios_t buffer by 1 byte" patch by Jeff Bezanson from Julia
--- a/iostream.c
+++ b/iostream.c
@@ -338,12 +338,14 @@
cv->len = n;
if (dest.buf != data) {
// outgrew initial space
- cv->data = dest.buf;
+ size_t sz;
+ cv->data = ios_takebuf(&dest, &sz);
#ifndef BOEHM_GC
cv_autorelease(cv);
#endif
+ } else {
+ ((char*)cv->data)[n] = '\0';
}
- ((char*)cv->data)[n] = '\0';
if (n == 0 && ios_eof(src))
return FL_EOF;
return str;
--- a/llt/ios.c
+++ b/llt/ios.c
@@ -127,12 +127,12 @@
// if we own the buffer we're free to resize it
// always allocate 1 bigger in case user wants to add a NUL
// terminator after taking over the buffer
- temp = LLT_REALLOC(s->buf, sz+1);
+ temp = LLT_REALLOC(s->buf, sz);
if (temp == nil)
return nil;
}
else {
- temp = LLT_ALLOC(sz+1);
+ temp = LLT_ALLOC(sz);
if (temp == nil)
return nil;
s->ownbuf = 1;
@@ -549,7 +549,7 @@
ios_flush(s);
- if (s->buf == &s->local[0]) {
+ if (s->buf == &s->local[0] || s->buf == nil || (!s->ownbuf && s->size == s->maxsize)) {
buf = LLT_ALLOC(s->size+1);
if (buf == nil)
return nil;
@@ -556,12 +556,17 @@
if (s->size)
memmove(buf, s->buf, s->size);
}
+ else if (s->size == s->maxsize) {
+ buf = LLT_REALLOC(s->buf, s->size + 1);
+ if (buf == nil)
+ return nil;
+ }
else {
buf = s->buf;
}
buf[s->size] = '\0';
- *psize = s->size+1; // buffer is actually 1 bigger for terminating NUL
+ *psize = s->size + 1;
/* empty stream and reinitialize */
_buf_init(s, s->bm);
--- a/llt/ios.h
+++ b/llt/ios.h
@@ -63,7 +63,7 @@
int ios_eof(ios_t *s);
int ios_flush(ios_t *s);
void ios_close(ios_t *s);
-char *ios_takebuf(ios_t *s, size_t *psize); // release buffer to caller
+char *ios_takebuf(ios_t *s, size_t *psize); // null-terminate and release buffer to caller
// set buffer space to use
int ios_setbuf(ios_t *s, char *buf, size_t size, int own);
int ios_bufmode(ios_t *s, bufmode_t mode);