MCPcopy Create free account
hub / github.com/BruceDevices/firmware / native_buffer_from

Function native_buffer_from

src/modules/bjs_interpreter/buffer_js.cpp:31–70  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

29}
30
31JSValue native_buffer_from(JSContext *ctx, JSValue *this_val, int argc, JSValue *argv) {
32 if (argc < 1 || !JS_IsString(ctx, argv[0])) {
33 return JS_ThrowTypeError(ctx, "Buffer.from: arg0 must be string");
34 }
35
36 const char *enc = NULL;
37 if (argc > 1 && !JS_IsUndefined(argv[1])) {
38 if (!JS_IsString(ctx, argv[1])) {
39 return JS_ThrowTypeError(ctx, "Buffer.from: arg1 must be string encoding");
40 }
41 JSCStringBuf enc_sb;
42 enc = JS_ToCString(ctx, argv[1], &enc_sb);
43 }
44
45 size_t input_len = 0;
46 JSCStringBuf input_sb;
47 const char *input = JS_ToCStringLen(ctx, &input_len, argv[0], &input_sb);
48 if (!input) { return JS_ThrowTypeError(ctx, "Buffer.from: invalid string"); }
49
50 JSValue bytes;
51 size_t out_len = 0;
52 if (!enc || strcmp(enc, "utf8") == 0 || strcmp(enc, "utf-8") == 0) {
53 bytes = JS_NewUint8ArrayCopy(ctx, (const uint8_t *)input, input_len);
54 out_len = input_len;
55 } else if (strcmp(enc, "base64") == 0) {
56 bytes = buffer_decode_base64(ctx, (const uint8_t *)input, input_len, &out_len);
57 } else {
58 return JS_ThrowTypeError(ctx, "Buffer.from: unsupported encoding");
59 }
60
61 if (JS_IsException(bytes)) { return bytes; }
62
63 JSValue obj = JS_NewObjectClassUser(ctx, JS_CLASS_BUFFER);
64 if (JS_IsException(obj)) { return obj; }
65
66 JS_SetPropertyStr(ctx, obj, "_data", bytes);
67 JS_SetPropertyStr(ctx, obj, "length", JS_NewUint32(ctx, out_len));
68
69 return obj;
70}
71
72JSValue native_buffer_toString(JSContext *ctx, JSValue *this_val, int argc, JSValue *argv) {
73 const char *enc = NULL;

Callers

nothing calls this directly

Calls 1

buffer_decode_base64Function · 0.85

Tested by

no test coverage detected