Skip to content

Commit

Permalink
Buffer#toString throw on unsupported encodings
Browse files Browse the repository at this point in the history
  • Loading branch information
SheetJSDev committed Sep 7, 2021
1 parent 076bcec commit 77364be
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
14 changes: 13 additions & 1 deletion src-input/duk_bi_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -1183,6 +1183,7 @@ DUK_INTERNAL duk_ret_t duk_bi_uint8array_plainof(duk_hthread *thr) {

#if defined(DUK_USE_BUFFEROBJECT_SUPPORT)
DUK_INTERNAL duk_ret_t duk_bi_nodejs_buffer_tostring(duk_hthread *thr) {
const char* encoding;
duk_hbufobj *h_this;
duk_int_t start_offset, end_offset;
duk_uint8_t *buf_slice;
Expand All @@ -1196,7 +1197,18 @@ DUK_INTERNAL duk_ret_t duk_bi_nodejs_buffer_tostring(duk_hthread *thr) {
}
DUK_HBUFOBJ_ASSERT_VALID(h_this);

/* Ignore encoding for now. */
/* TODO: support other encodings. currently only 'utf8' is supported. */
if (duk_is_undefined(thr, 0)) {
encoding = "utf8";
} else if (duk_is_string(thr, 0)) {
encoding = duk_to_string(thr, 0);
DUK_ASSERT(duk_is_string(thr, 0));
if(DUK_STRCMP(encoding, "utf8") != 0) {
DUK_DCERROR_TYPE_INVALID_ARGS(thr);
}
} else {
DUK_DCERROR_TYPE_INVALID_ARGS(thr);
}

duk__clamp_startend_nonegidx_noshift(thr,
(duk_int_t) h_this->length,
Expand Down
10 changes: 5 additions & 5 deletions tests/ecmascript/test-bi-nodejs-buffer-tostring.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@ false
true
"ABC"
"ABC"
"ABC"
"DEFG"
"EFG"
"E"
Expand Down Expand Up @@ -241,20 +240,21 @@ function nodejsBufferToStringTest() {
// buf.toString([encoding], [start], [end])

// Without arguments encoding defaults to UTF-8 and the entire
// buffer is converted to string. At least undefined and null
// buffer is converted to string. At least undefined is
// are accepted as "not defined" for encoding.
b = new Buffer('ABC');
safePrintString(b.toString());
safePrintString(b.toString(undefined));
safePrintString(b.toString(null));
// null is not a valid encoding
try { safePrintString(b.toString(null)); } catch(e) { }

// If the buffer is a slice of an underlying buffer, only that slice
// is string converted. Offsets are relative to the slice.
b = new Buffer('ABCDEFGH');
b = b.slice(3, 7); // DEFG
safePrintString(b.toString());
safePrintString(b.toString(null, 1));
safePrintString(b.toString(null, 1, 2));
safePrintString(b.toString(undefined, 1));
safePrintString(b.toString(undefined, 1, 2));

// When the buffer data is legal UTF-8 and the chosen encoding
// is UTF-8 (default), Duktape internal representation is correct
Expand Down

0 comments on commit 77364be

Please sign in to comment.