From 2c47b7beb1ed707ca951abbb7755f4d4b2d0548a Mon Sep 17 00:00:00 2001 From: Cryse Hillmes Date: Tue, 16 Apr 2024 14:46:22 +0800 Subject: [PATCH] Expose public equality comparison and sameness public API. (#373) * Expose public equality comparison and sameness public API. - add `JS_IsEqual` (operator `==`), returns an `int`: `-1` if an exception was thrown - add `JS_IsStrictEqual` (operator `===`) always succeeds, returns a `JS_BOOL` - add `JS_IsSameValue` always succeeds, returns a `JS_BOOL` - add `JS_IsSameValueZero` always succeeds, returns a `JS_BOOL` --- quickjs.c | 24 ++++++++++++++++++++++++ quickjs.h | 7 +++++++ 2 files changed, 31 insertions(+) diff --git a/quickjs.c b/quickjs.c index 575b969..1cb694b 100644 --- a/quickjs.c +++ b/quickjs.c @@ -51915,6 +51915,30 @@ void JS_AddPerformance(JSContext *ctx) JS_FreeValue(ctx, performance); } +/* Equality comparisons and sameness */ +int JS_IsEqual(JSContext *ctx, JSValue op1, JSValue op2) +{ + JSValue sp[2] = { js_dup(op1), js_dup(op2) }; + if (js_eq_slow(ctx, endof(sp), 0)) + return -1; + return JS_VALUE_GET_BOOL(sp[0]); +} + +JS_BOOL JS_IsStrictEqual(JSContext *ctx, JSValue op1, JSValue op2) +{ + return js_strict_eq2(ctx, js_dup(op1), js_dup(op2), JS_EQ_STRICT); +} + +JS_BOOL JS_IsSameValue(JSContext *ctx, JSValue op1, JSValue op2) +{ + return js_same_value(ctx, op1, op2); +} + +JS_BOOL JS_IsSameValueZero(JSContext *ctx, JSValue op1, JSValue op2) +{ + return js_same_value_zero(ctx, op1, op2); +} + /* WeakRef */ typedef struct JSWeakRefData { diff --git a/quickjs.h b/quickjs.h index d7cbde3..2560f5d 100644 --- a/quickjs.h +++ b/quickjs.h @@ -334,6 +334,13 @@ JS_EXTERN void JS_AddIntrinsicBigInt(JSContext *ctx); JS_EXTERN void JS_AddIntrinsicWeakRef(JSContext *ctx); JS_EXTERN void JS_AddPerformance(JSContext *ctx); +/* for equality comparisons and sameness */ +JS_EXTERN int JS_IsEqual(JSContext *ctx, JSValue op1, JSValue op2); +JS_EXTERN JS_BOOL JS_IsStrictEqual(JSContext *ctx, JSValue op1, JSValue op2); +JS_EXTERN JS_BOOL JS_IsSameValue(JSContext *ctx, JSValue op1, JSValue op2); +/* Similar to same-value equality, but +0 and -0 are considered equal. */ +JS_EXTERN JS_BOOL JS_IsSameValueZero(JSContext *ctx, JSValue op1, JSValue op2); + /* Only used for running 262 tests. TODO(saghul) add build time flag. */ JS_EXTERN JSValue js_string_codePointRange(JSContext *ctx, JSValue this_val, int argc, JSValue *argv);