Skip to content

Commit

Permalink
Merge pull request #1267 from MasterDuke17/let_encode_take_a_prealloc…
Browse files Browse the repository at this point in the history
…ated_buffer

Let encode take a preallocated buffer
  • Loading branch information
jnthn committed Apr 17, 2020
2 parents 6546027 + 0ce4cbe commit ab3f192
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
3 changes: 1 addition & 2 deletions lib/MAST/Nodes.nqp
Expand Up @@ -56,8 +56,7 @@ class MAST::Bytecode is repr('VMArray') is array_type(uint8) {
nqp::create(self)
}
method write_s(str $s) {
my @subbuf := nqp::encode($s, 'utf8', nqp::create(self));
self.write_buf(@subbuf);
nqp::encode($s, 'utf8', self);
}
method write_double(num $n) {
nqp::writenum(self, nqp::elems(self), $n, 13);
Expand Down
19 changes: 13 additions & 6 deletions src/strings/ops.c
Expand Up @@ -1785,8 +1785,6 @@ MVMObject * MVM_string_encode_to_buf_config(MVMThreadContext *tc, MVMString *s,
}
if (!elem_size)
MVM_exception_throw_adhoc(tc, "encode requires a native int array");
if (((MVMArray *)buf)->body.slots.any)
MVM_exception_throw_adhoc(tc, "encode requires an empty array");

/* At least find_encoding may allocate on first call, so root just
* in case. */
Expand All @@ -1797,10 +1795,19 @@ MVMObject * MVM_string_encode_to_buf_config(MVMThreadContext *tc, MVMString *s,
});

/* Stash the encoded data in the VMArray. */
((MVMArray *)buf)->body.slots.i8 = (MVMint8 *)encoded;
((MVMArray *)buf)->body.start = 0;
((MVMArray *)buf)->body.ssize = output_size / elem_size;
((MVMArray *)buf)->body.elems = output_size / elem_size;
if (((MVMArray *)buf)->body.slots.any) {
MVMuint32 prev_elems = ((MVMArray *)buf)->body.elems;
MVM_repr_pos_set_elems(tc, buf, ((MVMArray *)buf)->body.elems + output_size / elem_size);
memmove(((MVMArray *)buf)->body.slots.i8 + prev_elems, (MVMint8 *)encoded, output_size);
MVM_free(encoded);
}
else {
((MVMArray *)buf)->body.slots.i8 = (MVMint8 *)encoded;
((MVMArray *)buf)->body.start = 0;
((MVMArray *)buf)->body.ssize = output_size / elem_size;
((MVMArray *)buf)->body.elems = output_size / elem_size;
}

return buf;
}
MVMObject * MVM_string_encode_to_buf(MVMThreadContext *tc, MVMString *s, MVMString *enc_name,
Expand Down

0 comments on commit ab3f192

Please sign in to comment.