From 3f7a2c2197e7ccabf0c76530050d2d4ace07bc83 Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Wed, 28 Jun 2023 08:30:09 -0500 Subject: [PATCH] Try harder to avoid string copying with janet_getcbytes. --- src/core/capi.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/core/capi.c b/src/core/capi.c index be4f03e3..a89b4685 100644 --- a/src/core/capi.c +++ b/src/core/capi.c @@ -219,8 +219,9 @@ const char *janet_getcbytes(const Janet *argv, int32_t n) { /* Ensure buffer 0-padded */ if (janet_checktype(argv[n], JANET_BUFFER)) { JanetBuffer *b = janet_unwrap_buffer(argv[n]); - if (b->gc.flags & JANET_BUFFER_FLAG_NO_REALLOC) { - /* Make a copy with janet_smalloc in the rare case we have a buffer that cannot be realloced */ + if ((b->gc.flags & JANET_BUFFER_FLAG_NO_REALLOC) && b->count == b->capacity) { + /* Make a copy with janet_smalloc in the rare case we have a buffer that + * cannot be realloced and pushing a 0 byte would panic. */ char *new_string = janet_smalloc(b->count + 1); memcpy(new_string, b->data, b->count); new_string[b->count] = 0;