1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-28 11:09:54 +00:00

Update janet_getcbytes to padd buffers with trailing 0.

This commit is contained in:
Calvin Rose 2023-06-28 08:18:43 -05:00
parent 0cd00da354
commit f6248369fe

View File

@ -216,12 +216,31 @@ const char *janet_getcstring(const Janet *argv, int32_t n) {
} }
const char *janet_getcbytes(const Janet *argv, int32_t n) { 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 */
char *new_string = janet_smalloc(b->count + 1);
memcpy(new_string, b->data, b->count);
new_string[b->count] = 0;
if (strlen(new_string) != (size_t) b->count) goto badzeros;
return new_string;
} else {
/* Ensure trailing 0 */
janet_buffer_push_u8(b, 0);
b->count--;
if (strlen((char *)b->data) != (size_t) b->count) goto badzeros;
return (const char *) b->data;
}
}
JanetByteView view = janet_getbytes(argv, n); JanetByteView view = janet_getbytes(argv, n);
const char *cstr = (const char *)view.bytes; const char *cstr = (const char *)view.bytes;
if (strlen(cstr) != (size_t) view.len) { if (strlen(cstr) != (size_t) view.len) goto badzeros;
janet_panic("bytes contain embedded 0s");
}
return cstr; return cstr;
badzeros:
janet_panic("bytes contain embedded 0s");
} }
const char *janet_optcbytes(const Janet *argv, int32_t argc, int32_t n, const char *dflt) { const char *janet_optcbytes(const Janet *argv, int32_t argc, int32_t n, const char *dflt) {