Obsolete since JSAPI 19
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

Convert a 16-bit string to an 8-bit string.

Syntax

JSBool
JS_EncodeCharacters(JSContext *cx, const jschar *src, size_t srclen,
                    char *dst, size_t *dstlen);
Name Type Description
cx JSContext * A context.
src const jschar * The pointer to 16-bit values of JSString. This can be obtained with JS_GetStringChars.
srclen size_t The length of the source string, in 16-bit values.
dst const char * The pointer to an array of bytes to be filled with encoded characters; or NULL. The caller is responsible for allocating and freeing this buffer.
dstlenp size_t * In/out parameter. On entry, if dst is non-null, *dstlenp must be the length of the destination string in 16-bit units. On success, *dstlenp receives the length of the converted string, in bytes. On failure, *dstlenp receives the number of bytes written to dst before the error occurred.

Description

JS_EncodeCharacters copies the characters of a jschar array into a char array, converting the 16-bit values to 8-bit values. If SpiderMonkey was built with JS_C_STRINGS_ARE_UTF8 defined or JS_SetCStringsAreUTF8 was called, the string is converted to UTF-8.  Otherwise each character is simply truncated to 8 bits.

If UTF-8 is turned on, the length of the encoded string may vary.  To calculate the number of bytes needed, call JS_EncodeCharacters twice, like this:

    /* Determine how many bytes to allocate. */
    size_t dstlen = 0;
    if (!JS_EncodeCharacters(cx, src, srclen, NULL, &dstlen))
        return JS_FALSE;

    /* Allocate. */
    char *dst = (char *) JS_malloc(cx, dstlen);
    if (dst == NULL)
        return JS_FALSE;

    /* Convert characters to bytes. */
    JS_EncodeCharacters(cx, src, srclen, dst, &dstlen);

    /* Use the converted bytes for something. */
    ...

    /* Remember to free the bytes afterwards. */
    JS_free(cx, dst);
    return JS_TRUE;

On success, JS_EncodeCharacters sets *dstlenp to the real result length and returns JS_TRUE. Otherwise it reports an error and returns JS_FALSE.  This happens if the destination is too small for the resulting string or if the source buffer isn't proper UTF-16 because it contains unpaired surrogate values.

The user is responsible for allocating and freeing the memory of the destination string.

JS_EncodeCharacters never adds a trailing null character. To obtain a null-terminated string, allocate an extra byte for the null character and set it manually.

To convert bytes to jschars, the opposite conversion, use JS_DecodeBytes. To convert a JSString to a C char string, use JS_EncodeString or JS_GetStringBytes.

See Also