Add JS_Newsymbol, an API for creating symbols

Example usage:

~~~
JSValue global = JS_GetGlobalObject(ctx);
JSValue sym = JS_NewSymbol(ctx, "my.secret.thing", TRUE);
JSAtom atom = JS_ValueToAtom(ctx, sym);
JS_DefinePropertyValue(ctx, global, atom, JS_NewString(ctx, "qjs!"), JS_PROP_C_W_E);
JS_FreeAtom(ctx, atom);
JS_FreeValue(ctx, sym);
JS_FreeValue(ctx, global);
~~~
This commit is contained in:
Saúl Ibarra Corretgé 2024-03-23 23:44:47 +01:00
parent 5e5b00c48c
commit 4a66289af4
2 changed files with 14 additions and 4 deletions

View file

@ -2970,7 +2970,7 @@ static JSAtom JS_NewAtomInt64(JSContext *ctx, int64_t n)
}
/* 'p' is freed */
static JSValue JS_NewSymbol(JSContext *ctx, JSString *p, int atom_type)
static JSValue JS_NewSymbolInternal(JSContext *ctx, JSString *p, int atom_type)
{
JSRuntime *rt = ctx->rt;
JSAtom atom;
@ -2991,7 +2991,15 @@ static JSValue JS_NewSymbolFromAtom(JSContext *ctx, JSAtom descr,
assert(descr < rt->atom_size);
p = rt->atom_array[descr];
js_dup(JS_MKPTR(JS_TAG_STRING, p));
return JS_NewSymbol(ctx, p, atom_type);
return JS_NewSymbolInternal(ctx, p, atom_type);
}
JSValue JS_NewSymbol(JSContext *ctx, const char *description, JS_BOOL is_global)
{
JSAtom atom = JS_NewAtom(ctx, description);
if (atom == JS_ATOM_NULL)
return JS_EXCEPTION;
return JS_NewSymbolFromAtom(ctx, atom, is_global ? JS_ATOM_TYPE_GLOBAL_SYMBOL : JS_ATOM_TYPE_SYMBOL);
}
#define ATOM_GET_STR_BUF_SIZE 64
@ -44324,7 +44332,7 @@ static JSValue js_symbol_constructor(JSContext *ctx, JSValue new_target,
return JS_EXCEPTION;
p = JS_VALUE_GET_STRING(str);
}
return JS_NewSymbol(ctx, p, JS_ATOM_TYPE_SYMBOL);
return JS_NewSymbolInternal(ctx, p, JS_ATOM_TYPE_SYMBOL);
}
static JSValue js_thisSymbolValue(JSContext *ctx, JSValue this_val)
@ -44396,7 +44404,7 @@ static JSValue js_symbol_for(JSContext *ctx, JSValue this_val,
str = JS_ToString(ctx, argv[0]);
if (JS_IsException(str))
return JS_EXCEPTION;
return JS_NewSymbol(ctx, JS_VALUE_GET_STRING(str), JS_ATOM_TYPE_GLOBAL_SYMBOL);
return JS_NewSymbolInternal(ctx, JS_VALUE_GET_STRING(str), JS_ATOM_TYPE_GLOBAL_SYMBOL);
}
static JSValue js_symbol_keyFor(JSContext *ctx, JSValue this_val,

View file

@ -769,6 +769,8 @@ JS_EXTERN void JS_SetSharedArrayBufferFunctions(JSRuntime *rt, const JSSharedArr
JS_EXTERN JSValue JS_NewPromiseCapability(JSContext *ctx, JSValue *resolving_funcs);
JS_EXTERN JSValue JS_NewSymbol(JSContext *ctx, const char *description, JS_BOOL is_global);
/* is_handled = TRUE means that the rejection is handled */
typedef void JSHostPromiseRejectionTracker(JSContext *ctx, JSValue promise,
JSValue reason,