Bug 1963431: Add JS_StringifyWithLengthHint r=tcampbell

Differential Revision: https://phabricator.services.mozilla.com/D247145
This commit is contained in:
Iain Ireland
2025-04-29 18:44:10 +00:00
parent 8d7f820172
commit a8b24ef5ed
2 changed files with 19 additions and 0 deletions

View File

@@ -26,12 +26,19 @@ using JSONWriteCallback = bool (*)(const char16_t* buf, uint32_t len,
* *
* In cases where JSON.stringify would return undefined, this function calls * In cases where JSON.stringify would return undefined, this function calls
* |callback| with the string "null". * |callback| with the string "null".
*
* If a length hint is passed, space will be reserved for at least that many
* characters.
*/ */
extern JS_PUBLIC_API bool JS_Stringify(JSContext* cx, extern JS_PUBLIC_API bool JS_Stringify(JSContext* cx,
JS::MutableHandle<JS::Value> value, JS::MutableHandle<JS::Value> value,
JS::Handle<JSObject*> replacer, JS::Handle<JSObject*> replacer,
JS::Handle<JS::Value> space, JS::Handle<JS::Value> space,
JSONWriteCallback callback, void* data); JSONWriteCallback callback, void* data);
extern JS_PUBLIC_API bool JS_StringifyWithLengthHint(
JSContext* cx, JS::MutableHandle<JS::Value> value,
JS::Handle<JSObject*> replacer, JS::Handle<JS::Value> space,
JSONWriteCallback callback, void* data, size_t lengthHint);
namespace JS { namespace JS {

View File

@@ -3665,6 +3665,15 @@ JS_PUBLIC_API bool JS::PropertySpecNameEqualsId(JSPropertySpec::Name name,
JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp, JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp,
HandleObject replacer, HandleValue space, HandleObject replacer, HandleValue space,
JSONWriteCallback callback, void* data) { JSONWriteCallback callback, void* data) {
return JS_StringifyWithLengthHint(cx, vp, replacer, space, callback, data, 0);
}
JS_PUBLIC_API bool JS_StringifyWithLengthHint(JSContext* cx,
MutableHandleValue vp,
HandleObject replacer,
HandleValue space,
JSONWriteCallback callback,
void* data, size_t lengthHint) {
AssertHeapIsIdle(); AssertHeapIsIdle();
CHECK_THREAD(cx); CHECK_THREAD(cx);
cx->check(replacer, space); cx->check(replacer, space);
@@ -3672,6 +3681,9 @@ JS_PUBLIC_API bool JS_Stringify(JSContext* cx, MutableHandleValue vp,
if (!sb.ensureTwoByteChars()) { if (!sb.ensureTwoByteChars()) {
return false; return false;
} }
if (lengthHint && !sb.reserve(lengthHint)) {
return false;
}
if (!Stringify(cx, vp, replacer, space, sb, StringifyBehavior::Normal)) { if (!Stringify(cx, vp, replacer, space, sb, StringifyBehavior::Normal)) {
return false; return false;
} }