MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

JS::DeflateStringToUTF8Buffer

This article covers features introduced in SpiderMonkey 38

Encode the given string as UTF8 into given buffer.

Syntax

// New in JSAPI 52
void
DeflateStringToUTF8Buffer(JSFlatString* src, mozilla::RangedPtr<char> dst,
                          size_t* dstlenp = nullptr, size_t* numcharsp = nullptr);

// Obsolete in SpiderMonkey 49
void
DeflateStringToUTF8Buffer(JSFlatString* src, mozilla::RangedPtr<char> dst);
Name Type Description
src JSFlatString * The pointer to the string to deflate.
dst mozilla::RangedPtr<char> The ranged pointer to the buffer.
dstlenp size_t* The pointer to receive the number of bytes written to the buffer.
numcharsp size_t* The pointer to receive the number of Unicode characters written to the buffer.

Description

JS::DeflateStringToUTF8Buffer encodes src as UTF8. The caller must either ensure dst has enough space to encode the entire string, or pass the length of the buffer as dstlenp. In which case, the function will encode characters from the string until the buffer is exhausted. Does not write the null terminator.

If dstlenp is provided, it will be updated to hold the number of bytes written to the buffer. If numcharsp is provided, it will be updated to hold the number of Unicode characters written to the buffer. This can be less than the length of the string, if the buffer is exhausted before the string is fully encoded.

Examples

char16_t uchars[] = { 0xD83E, 0xDD8A, 0 };

JS::RootedString str(cx, JS_NewUCStringCopyN(cx, uchars, 2));
if (!str) return false;

JS::Rooted<JSFlatString*> flatStr(cx, JS_FlattenString(cx, str));
if (!flatStr) return false;

size_t length = JS::GetDeflatedUTF8StringLength(flatStr);

char* buffer = static_cast<char*>(JS_malloc(cx, length + 1));
if (!buffer) return false;

JS::DeflateStringToUTF8Buffer(flatStr, mozilla::RangedPtr<char>(buffer, length));
buffer[length] = '\0';

printf("utf8: [%s]\n", buffer);

JS_free(cx, buffer);

See Also

Document Tags and Contributors

 Contributors to this page: bunnybooboo, arai
 Last updated by: bunnybooboo,