tildefriends/src/util.js.c

90 lines
2.3 KiB
C
Raw Normal View History

#include "util.js.h"
#include "task.h"
static JSValue _util_utf8_decode(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
JSValue result = JS_NULL;
size_t length;
if (JS_IsString(argv[0]))
{
result = JS_DupValue(context, argv[0]);
}
else
{
uint8_t* array = tf_util_try_get_array_buffer(context, &length, argv[0]);
if (array)
{
result = JS_NewStringLen(context, (const char*)array, length);
}
else
{
size_t offset;
size_t element_size;
JSValue buffer = tf_util_try_get_typed_array_buffer(context, argv[0], &offset, &length, &element_size);
size_t size;
if (!JS_IsException(buffer))
{
array = tf_util_try_get_array_buffer(context, &size, buffer);
if (array)
{
result = JS_NewStringLen(context, (const char*)array, size);
}
}
JS_FreeValue(context, buffer);
}
}
return result;
}
JSValue tf_util_utf8_decode(JSContext* context, JSValue value)
{
return _util_utf8_decode(context, JS_NULL, 1, &value);
}
uint8_t* tf_util_try_get_array_buffer(JSContext *ctx, size_t *psize, JSValueConst obj)
{
uint8_t* result = JS_GetArrayBuffer(ctx, psize, obj);
JS_FreeValue(ctx, JS_GetException(ctx));
return result;
}
JSValue tf_util_try_get_typed_array_buffer(JSContext *ctx, JSValueConst obj, size_t *pbyte_offset, size_t *pbyte_length, size_t *pbytes_per_element)
{
JSValue result = JS_GetTypedArrayBuffer(ctx, obj, pbyte_offset, pbyte_length, pbytes_per_element);
JS_FreeValue(ctx, JS_GetException(ctx));
return result;
}
JSValue _util_print(JSContext* context, JSValueConst this_val, int argc, JSValueConst* argv)
{
tf_task_t* task = JS_GetContextOpaque(context);
if (task)
{
printf("Task[%p:%s]>", task, tf_task_get_name(task));
}
for (int i = 0; i < argc; ++i)
{
if (JS_IsNull(argv[i]))
{
printf(" null");
}
else
{
const char* value = JS_ToCString(context, argv[i]);
printf(" %s", value);
JS_FreeCString(context, value);
}
}
printf("\n");
return JS_NULL;
}
void tf_util_register(JSContext* context)
{
JSValue global = JS_GetGlobalObject(context);
JS_SetPropertyStr(context, global, "utf8Decode", JS_NewCFunction(context, _util_utf8_decode, "utf8Decode", 1));
JS_SetPropertyStr(context, global, "print", JS_NewCFunction(context, _util_print, "print", 1));
JS_FreeValue(context, global);
}