summaryrefslogtreecommitdiff
path: root/gjs/byteArray.cpp
blob: 59f55dfc8f71cea2c9b5682628c577dc427003b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
/* -*- mode: C++; c-basic-offset: 4; indent-tabs-mode: nil; -*- */
/*
 * Copyright (c) 2010  litl, LLC
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include <config.h>
#include <string.h>
#include <glib.h>
#include "byteArray.h"
#include "gi/boxed.h"
#include "jsapi-class.h"
#include "jsapi-wrapper.h"
#include "jsapi-util-args.h"
#include <girepository.h>
#include <util/log.h>

typedef struct {
    GByteArray *array;
    GBytes     *bytes;
} ByteArrayInstance;

extern struct JSClass gjs_byte_array_class;
GJS_DEFINE_PRIV_FROM_JS(ByteArrayInstance, gjs_byte_array_class)

static bool   byte_array_get_prop      (JSContext    *context,
                                        JS::HandleObject obj,
                                        JS::HandleId id,
                                        JS::MutableHandleValue value_p);
static bool   byte_array_set_prop      (JSContext    *context,
                                        JS::HandleObject obj,
                                        JS::HandleId id,
                                        JS::MutableHandleValue value_p,
                                        JS::ObjectOpResult&    result);
GJS_NATIVE_CONSTRUCTOR_DECLARE(byte_array);
static void   byte_array_finalize      (JSFreeOp     *fop,
                                        JSObject     *obj);

static JSObject *gjs_byte_array_get_proto(JSContext *);

static const struct JSClassOps gjs_byte_array_class_ops = {
    NULL,  /* addProperty */
    NULL,  /* deleteProperty */
    byte_array_get_prop,
    byte_array_set_prop,
    NULL,  /* enumerate */
    NULL,  /* resolve */
    nullptr,  /* mayResolve */
    byte_array_finalize
};

struct JSClass gjs_byte_array_class = {
    "ByteArray",
    JSCLASS_HAS_PRIVATE | JSCLASS_BACKGROUND_FINALIZE,
    &gjs_byte_array_class_ops
};

bool
gjs_typecheck_bytearray(JSContext       *context,
                        JS::HandleObject object,
                        bool             throw_error)
{
    return do_base_typecheck(context, object, throw_error);
}

static JS::Value
gjs_value_from_gsize(gsize v)
{
    if (v <= (gsize) JSVAL_INT_MAX) {
        return JS::Int32Value(v);
    }
    return JS::NumberValue(v);
}

static void
byte_array_ensure_array (ByteArrayInstance  *priv)
{
    if (priv->bytes) {
        priv->array = g_bytes_unref_to_array(priv->bytes);
        priv->bytes = NULL;
    } else {
        g_assert(priv->array);
    }
}

static void
byte_array_ensure_gbytes (ByteArrayInstance  *priv)
{
    if (priv->array) {
        priv->bytes = g_byte_array_free_to_bytes(priv->array);
        priv->array = NULL;
    } else {
        g_assert(priv->bytes);
    }
}

static bool
gjs_value_to_gsize(JSContext         *context,
                   JS::HandleValue    value,
                   gsize             *v_p)
{
    guint32 val32;

    /* Just JS::ToUint32() would work. However, we special case ints for a nicer
     * error message on negative indices.
     */
    if (value.isInt32()) {
        int i = value.toInt32();
        if (i < 0) {
            gjs_throw(context, "Negative length or index %d is not allowed for ByteArray",
                      i);
            return false;
        }
        *v_p = i;
        return true;
    } else {
        bool ret;
        /* This is pretty liberal (it converts about anything to
         * a number) but it's what we use elsewhere in gjs too.
         */

        ret = JS::ToUint32(context, value, &val32);
        *v_p = val32;
        return ret;
    }
}

static bool
gjs_value_to_byte(JSContext         *context,
                  JS::HandleValue    value,
                  guint8            *v_p)
{
    gsize v;

    if (!gjs_value_to_gsize(context, value, &v))
        return false;

    if (v >= 256) {
        gjs_throw(context,
                  "Value %" G_GSIZE_FORMAT " is not a valid byte; must be in range [0,255]",
                  v);
        return false;
    }

    *v_p = v;
    return true;
}

static bool
byte_array_get_index(JSContext         *context,
                     JS::HandleObject obj,
                     ByteArrayInstance *priv,
                     gsize              idx,
                     JS::MutableHandleValue value_p)
{
    gsize len;
    guint8 *data;
    
    gjs_byte_array_peek_data(context, obj, &data, &len);

    if (idx >= len) {
        gjs_throw(context,
                  "Index %" G_GSIZE_FORMAT " is out of range for ByteArray length %lu",
                  idx,
                  (unsigned long)len);
        return false;
    }

    value_p.setInt32(data[idx]);

    return true;
}

/* a hook on getting a property; set value_p to override property's value.
 * Return value is false on OOM/exception.
 */
static bool
byte_array_get_prop(JSContext *context,
                    JS::HandleObject obj,
                    JS::HandleId id,
                    JS::MutableHandleValue value_p)
{
    ByteArrayInstance *priv;

    priv = priv_from_js(context, obj);

    if (!priv)
        return true; /* prototype, not an instance. */

    JS::RootedValue id_value(context);
    if (!JS_IdToValue(context, id, &id_value))
        return false;

    /* First handle array indexing */
    if (id_value.isNumber()) {
        gsize idx;
        if (!gjs_value_to_gsize(context, id_value, &idx))
            return false;
        return byte_array_get_index(context, obj, priv, idx, value_p);
    }

    /* We don't special-case anything else for now. Regular JS arrays
     * allow string versions of ints for the index, we don't bother.
     */

    return true;
}

static bool
byte_array_length_getter(JSContext *context,
                         unsigned   argc,
                         JS::Value *vp)
{
    GJS_GET_PRIV(context, argc, vp, args, to, ByteArrayInstance, priv);
    gsize len = 0;

    if (!priv)
        return true; /* prototype, not an instance. */

    if (priv->array != NULL)
        len = priv->array->len;
    else if (priv->bytes != NULL)
        len = g_bytes_get_size (priv->bytes);
    args.rval().set(gjs_value_from_gsize(len));
    return true;
}

static bool
byte_array_length_setter(JSContext *context,
                         unsigned   argc,
                         JS::Value *vp)
{
    GJS_GET_PRIV(context, argc, vp, args, to, ByteArrayInstance, priv);
    gsize len = 0;

    if (!priv)
        return true; /* prototype, not instance */

    byte_array_ensure_array(priv);

    if (!gjs_value_to_gsize(context, args[0], &len)) {
        gjs_throw(context,
                  "Can't set ByteArray length to non-integer");
        return false;
    }
    g_byte_array_set_size(priv->array, len);
    args.rval().setUndefined();
    return true;
}

static bool
byte_array_set_index(JSContext         *context,
                     JS::HandleObject obj,
                     ByteArrayInstance *priv,
                     gsize              idx,
                     JS::MutableHandleValue value_p,
                     JS::ObjectOpResult&    result)
{
    guint8 v;

    if (!gjs_value_to_byte(context, value_p, &v)) {
        return false;
    }

    byte_array_ensure_array(priv);

    /* grow the array if necessary */
    if (idx >= priv->array->len) {
        g_byte_array_set_size(priv->array,
                              idx + 1);
    }

    g_array_index(priv->array, guint8, idx) = v;

    /* Stop JS from storing a copy of the value */
    value_p.setUndefined();

    return result.succeed();
}

/* a hook on setting a property; set value_p to override property value to
 * be set. Return value is false on OOM/exception.
 */
static bool
byte_array_set_prop(JSContext *context,
                    JS::HandleObject obj,
                    JS::HandleId id,
                    JS::MutableHandleValue value_p,
                    JS::ObjectOpResult&    result)
{
    ByteArrayInstance *priv;

    priv = priv_from_js(context, obj);

    if (!priv)
        return result.succeed(); /* prototype, not an instance. */

    JS::RootedValue id_value(context);
    if (!JS_IdToValue(context, id, &id_value))
        return false;

    /* First handle array indexing */
    if (id_value.isNumber()) {
        gsize idx;
        if (!gjs_value_to_gsize(context, id_value, &idx))
            return false;

        return byte_array_set_index(context, obj, priv, idx, value_p, result);
    }

    /* We don't special-case anything else for now */

    return result.succeed();
}

static GByteArray *
gjs_g_byte_array_new(int preallocated_length)
{
    GByteArray *array;

    /* can't use g_byte_array_new() because we need to clear to zero.
     * We nul-terminate too for ease of toString() and for security
     * paranoia.
     */
    array =  (GByteArray*) g_array_sized_new (true, /* nul-terminated */
                                              true, /* clear to zero */
                                              1, /* element size */
                                              preallocated_length);
   if (preallocated_length > 0) {
       /* we want to not only allocate the size, but have it
        * already be the array's length.
        */
       g_byte_array_set_size(array, preallocated_length);
   }

   return array;
}

GJS_NATIVE_CONSTRUCTOR_DECLARE(byte_array)
{
    GJS_NATIVE_CONSTRUCTOR_VARIABLES(byte_array)
    ByteArrayInstance *priv;
    gsize preallocated_length;

    GJS_NATIVE_CONSTRUCTOR_PRELUDE(byte_array);

    preallocated_length = 0;
    if (argc >= 1) {
        if (!gjs_value_to_gsize(context, argv[0], &preallocated_length)) {
            gjs_throw(context,
                      "Argument to ByteArray constructor should be a positive number for array length");
            return false;
        }
    }

    priv = g_slice_new0(ByteArrayInstance);
    priv->array = gjs_g_byte_array_new(preallocated_length);
    g_assert(priv_from_js(context, object) == NULL);
    JS_SetPrivate(object, priv);

    GJS_NATIVE_CONSTRUCTOR_FINISH(byte_array);

    return true;
}

static void
byte_array_finalize(JSFreeOp *fop,
                    JSObject *obj)
{
    ByteArrayInstance *priv;

    priv = (ByteArrayInstance*) JS_GetPrivate(obj);

    if (!priv)
        return; /* prototype, not instance */

    if (priv->array) {
        g_byte_array_free(priv->array, true);
        priv->array = NULL;
    } else if (priv->bytes) {
        g_clear_pointer(&priv->bytes, g_bytes_unref);
    }

    g_slice_free(ByteArrayInstance, priv);
}

/* implement toString() with an optional encoding arg */
static bool
to_string_func(JSContext *context,
               unsigned   argc,
               JS::Value *vp)
{
    GJS_GET_PRIV(context, argc, vp, argv, to, ByteArrayInstance, priv);
    GjsAutoJSChar encoding;
    bool encoding_is_utf8;
    gchar *data;

    if (!priv)
        return true; /* prototype, not instance */

    byte_array_ensure_array(priv);

    if (argc >= 1 && argv[0].isString()) {
        JS::RootedString str(context, argv[0].toString());
        encoding = JS_EncodeStringToUTF8(context, str);
        if (!encoding)
            return false;

        /* maybe we should be smarter about utf8 synonyms here.
         * doesn't matter much though. encoding_is_utf8 is
         * just an optimization anyway.
         */
        encoding_is_utf8 = (strcmp(encoding, "UTF-8") == 0);
    } else {
        encoding_is_utf8 = true;
    }

    if (priv->array->len == 0)
        /* the internal data pointer could be NULL in this case */
        data = (gchar*)"";
    else
        data = (gchar*)priv->array->data;

    if (encoding_is_utf8) {
        /* optimization, avoids iconv overhead and runs
         * libmozjs hardwired utf8-to-utf16
         */
        return gjs_string_from_utf8_n(context, data, priv->array->len, argv.rval());
    } else {
        bool ok = false;
        gsize bytes_written;
        GError *error;
        JSString *s;
        char *u16_str;
        char16_t *u16_out;

        error = NULL;
        u16_str = g_convert(data,
                           priv->array->len,
                           "UTF-16",
                           encoding,
                           NULL, /* bytes read */
                           &bytes_written,
                           &error);
        if (u16_str == NULL) {
            /* frees the GError */
            gjs_throw_g_error(context, error);
            return false;
        }

        /* bytes_written should be bytes in a UTF-16 string so
         * should be a multiple of 2
         */
        g_assert((bytes_written % 2) == 0);

        u16_out = g_new(char16_t, bytes_written / 2);
        memcpy(u16_out, u16_str, bytes_written);
        s = JS_NewUCStringCopyN(context, u16_out, bytes_written / 2);
        if (s != NULL) {
            ok = true;
            argv.rval().setString(s);
        }

        g_free(u16_str);
        g_free(u16_out);
        return ok;
    }
}

static bool
to_gbytes_func(JSContext *context,
               unsigned   argc,
               JS::Value *vp)
{
    GJS_GET_PRIV(context, argc, vp, rec, to, ByteArrayInstance, priv);
    JSObject *ret_bytes_obj;
    GIBaseInfo *gbytes_info;

    if (!priv)
        return true; /* prototype, not instance */

    byte_array_ensure_gbytes(priv);

    gbytes_info = g_irepository_find_by_gtype(NULL, G_TYPE_BYTES);
    ret_bytes_obj = gjs_boxed_from_c_struct(context, (GIStructInfo*)gbytes_info,
                                            priv->bytes, GJS_BOXED_CREATION_NONE);

    rec.rval().setObjectOrNull(ret_bytes_obj);
    return true;
}

static JSObject*
byte_array_new(JSContext *context)
{
    ByteArrayInstance *priv;

    JS::RootedObject proto(context, gjs_byte_array_get_proto(context));
    JS::RootedObject array(context,
        JS_NewObjectWithGivenProto(context, &gjs_byte_array_class, proto));

    priv = g_slice_new0(ByteArrayInstance);

    g_assert(priv_from_js(context, array) == NULL);
    JS_SetPrivate(array, priv);

    return array;
}

/* fromString() function implementation */
static bool
from_string_func(JSContext *context,
                 unsigned   argc,
                 JS::Value *vp)
{
    JS::CallArgs argv = JS::CallArgsFromVp (argc, vp);
    ByteArrayInstance *priv;
    GjsAutoJSChar encoding;
    bool encoding_is_utf8;
    JS::RootedObject obj(context, byte_array_new(context));

    if (!obj)
        return false;

    priv = priv_from_js(context, obj);
    g_assert (priv != NULL);

    g_assert(argc > 0); /* because we specified min args 1 */

    priv->array = gjs_g_byte_array_new(0);

    if (!argv[0].isString()) {
        gjs_throw(context,
                  "byteArray.fromString() called with non-string as first arg");
        return false;
    }

    if (argc > 1 && argv[1].isString()) {
        JS::RootedString str(context, argv[1].toString());
        encoding = JS_EncodeStringToUTF8(context, str);
        if (!encoding)
            return false;

        /* maybe we should be smarter about utf8 synonyms here.
         * doesn't matter much though. encoding_is_utf8 is
         * just an optimization anyway.
         */
        encoding_is_utf8 = (strcmp(encoding, "UTF-8") == 0);
    } else {
        encoding_is_utf8 = true;
    }

    if (encoding_is_utf8) {
        /* optimization? avoids iconv overhead and runs
         * libmozjs hardwired utf16-to-utf8.
         */
        JS::RootedString str(context, argv[0].toString());
        GjsAutoJSChar utf8 = JS_EncodeStringToUTF8(context, str);
        if (!utf8)
            return false;

        g_byte_array_set_size(priv->array, 0);
        g_byte_array_append(priv->array,
                            reinterpret_cast<const guint8*>(utf8.get()),
                            strlen(utf8));
    } else {
        JSString *str = argv[0].toString();  /* Rooted by argv */
        GError *error = NULL;
        char *encoded = NULL;
        gsize bytes_written;

        /* Scope for AutoCheckCannotGC, will crash if a GC is triggered
         * while we are using the string's chars */
        {
            JS::AutoCheckCannotGC nogc;
            size_t len;

            if (JS_StringHasLatin1Chars(str)) {
                const JS::Latin1Char *chars =
                    JS_GetLatin1StringCharsAndLength(context, nogc, str, &len);
                if (chars == NULL)
                    return false;

                encoded = g_convert((char *) chars, len,
                                    encoding,  /* to_encoding */
                                    "LATIN1",  /* from_encoding */
                                    NULL,  /* bytes read */
                                    &bytes_written, &error);
            } else {
                const char16_t *chars =
                    JS_GetTwoByteStringCharsAndLength(context, nogc, str, &len);
                if (chars == NULL)
                    return false;

                encoded = g_convert((char *) chars, len * 2,
                                    encoding,  /* to_encoding */
                                    "UTF-16",  /* from_encoding */
                                    NULL,  /* bytes read */
                                    &bytes_written, &error);
            }
        }

        if (encoded == NULL) {
            /* frees the GError */
            gjs_throw_g_error(context, error);
            return false;
        }

        g_byte_array_set_size(priv->array, 0);
        g_byte_array_append(priv->array, (guint8*) encoded, bytes_written);

        g_free(encoded);
    }

    argv.rval().setObject(*obj);
    return true;
}

/* fromArray() function implementation */
static bool
from_array_func(JSContext *context,
                unsigned   argc,
                JS::Value *vp)
{
    JS::CallArgs argv = JS::CallArgsFromVp (argc, vp);
    ByteArrayInstance *priv;
    guint32 len;
    guint32 i;
    bool is_array;
    JS::RootedObject obj(context, byte_array_new(context));

    if (!obj)
        return false;

    priv = priv_from_js(context, obj);
    g_assert (priv != NULL);

    g_assert(argc > 0); /* because we specified min args 1 */

    priv->array = gjs_g_byte_array_new(0);

    JS::RootedObject array_obj(context, &argv[0].toObject());
    if (!JS_IsArrayObject(context, array_obj, &is_array))
        return false;
    if (!is_array) {
        gjs_throw(context,
                  "byteArray.fromArray() called with non-array as first arg");
        return false;
    }

    if (!JS_GetArrayLength(context, array_obj, &len)) {
        gjs_throw(context,
                  "byteArray.fromArray() can't get length of first array arg");
        return false;
    }

    g_byte_array_set_size(priv->array, len);

    JS::RootedValue elem(context);
    for (i = 0; i < len; ++i) {
        guint8 b;

        elem = JS::UndefinedValue();
        if (!JS_GetElement(context, array_obj, i, &elem)) {
            /* this means there was an exception, while elem.isUndefined()
             * means no element found
             */
            return false;
        }

        if (elem.isUndefined())
            continue;

        if (!gjs_value_to_byte(context, elem, &b))
            return false;

        g_array_index(priv->array, guint8, i) = b;
    }

    argv.rval().setObject(*obj);
    return true;
}

static bool
from_gbytes_func(JSContext *context,
                 unsigned   argc,
                 JS::Value *vp)
{
    JS::CallArgs argv = JS::CallArgsFromVp (argc, vp);
    JS::RootedObject bytes_obj(context);
    GBytes *gbytes;
    ByteArrayInstance *priv;

    if (!gjs_parse_call_args(context, "overrides_gbytes_to_array", argv, "o",
                             "bytes", &bytes_obj))
        return false;

    if (!gjs_typecheck_boxed(context, bytes_obj, NULL, G_TYPE_BYTES, true))
        return false;

    gbytes = (GBytes*) gjs_c_struct_from_boxed(context, bytes_obj);

    JS::RootedObject obj(context, byte_array_new(context));
    if (!obj)
        return false;
    priv = priv_from_js(context, obj);
    g_assert (priv != NULL);

    priv->bytes = g_bytes_ref(gbytes);

    argv.rval().setObject(*obj);
    return true;
}

JSObject *
gjs_byte_array_from_byte_array (JSContext *context,
                                GByteArray *array)
{
    ByteArrayInstance *priv;

    g_return_val_if_fail(context != NULL, NULL);
    g_return_val_if_fail(array != NULL, NULL);

    JS::RootedObject proto(context, gjs_byte_array_get_proto(context));
    JS::RootedObject object(context,
        JS_NewObjectWithGivenProto(context, &gjs_byte_array_class, proto));

    if (!object) {
        gjs_throw(context, "failed to create byte array");
        return NULL;
    }

    priv = g_slice_new0(ByteArrayInstance);
    g_assert(priv_from_js(context, object) == NULL);
    JS_SetPrivate(object, priv);
    priv->array = g_byte_array_new();
    priv->array->data = (guint8*) g_memdup(array->data, array->len);
    priv->array->len = array->len;

    return object;
}

GBytes *
gjs_byte_array_get_bytes (JSContext       *context,
                          JS::HandleObject object)
{
    ByteArrayInstance *priv;
    priv = priv_from_js(context, object);
    g_assert(priv != NULL);

    byte_array_ensure_gbytes(priv);

    return g_bytes_ref (priv->bytes);
}

GByteArray *
gjs_byte_array_get_byte_array (JSContext       *context,
                               JS::HandleObject obj)
{
    ByteArrayInstance *priv;
    priv = priv_from_js(context, obj);
    g_assert(priv != NULL);

    byte_array_ensure_array(priv);

    return g_byte_array_ref (priv->array);
}

void
gjs_byte_array_peek_data (JSContext       *context,
                          JS::HandleObject obj,
                          guint8         **out_data,
                          gsize           *out_len)
{
    ByteArrayInstance *priv;
    priv = priv_from_js(context, obj);
    g_assert(priv != NULL);
    
    if (priv->array != NULL) {
        *out_data = (guint8*)priv->array->data;
        *out_len = (gsize)priv->array->len;
    } else if (priv->bytes != NULL) {
        *out_data = (guint8*)g_bytes_get_data(priv->bytes, out_len);
    } else {
        g_assert_not_reached();
    }
}

static JSPropertySpec gjs_byte_array_proto_props[] = {
    JS_PSGS("length", byte_array_length_getter, byte_array_length_setter,
            JSPROP_PERMANENT),
    JS_PS_END
};

static JSFunctionSpec gjs_byte_array_proto_funcs[] = {
    JS_FN("toString", to_string_func, 0, 0),
    JS_FN("toGBytes", to_gbytes_func, 0, 0),
    JS_FS_END};

static JSFunctionSpec *gjs_byte_array_static_funcs = nullptr;

static JSFunctionSpec gjs_byte_array_module_funcs[] = {
    JS_FN("fromString", from_string_func, 1, 0),
    JS_FN("fromArray", from_array_func, 1, 0),
    JS_FN("fromGBytes", from_gbytes_func, 1, 0),
    JS_FS_END};

GJS_DEFINE_PROTO_FUNCS(byte_array)

bool
gjs_define_byte_array_stuff(JSContext              *cx,
                            JS::MutableHandleObject module)
{
    module.set(JS_NewPlainObject(cx));

    JS::RootedObject proto(cx);
    return gjs_byte_array_define_proto(cx, module, &proto) &&
        JS_DefineFunctions(cx, module, gjs_byte_array_module_funcs);
}