Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-js

Source of release 0.6.1

0.6.1 / src / engine / array_buffer_methods.lucb

#==============================================================================================
#
#   array_buffer_methods - ArrayBuffer.prototype.transfer, resize and slice, and the
#                          ArrayBuffer and SharedArrayBuffer tables
#
#   DESCRIPTION:
#       Port of quickjs.c lines 57117-57357: js_array_buffer_transfer (transfer and
#       transferToFixedLength), js_array_buffer_resize (resize and grow),
#       js_array_buffer_slice and the function tables of both classes.
#
#==============================================================================================

# mark: transfer ================================================================================

# ES #sec-arraybuffer.prototype.transfer
## ArrayBuffer.prototype.transfer (transfer_to_fixed_length == 0) and
## transferToFixedLength (1).
func js_array_buffer_transfer(ctx: Context*, this_val: Value, argc: i32, argv: Value*,
                              transfer_to_fixed_length: i32) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)ClassId.array_buffer))
    if abuf.shared != 0:
        try js_throw_type_error(ctx, "cannot transfer a SharedArrayBuffer")
    var new_len: u64 = 0
    if argc < 1 or js_is_undefined(argv[0]):
        new_len = (u64)abuf.byte_length
    else:
        try js_to_index(ctx, &new_len, argv[0])
    if abuf.detached != 0:
        try js_throw_type_error_detached_array_buffer(ctx)
    var max_len: u64 = 0
    var pmax_len: u64*? = none
    if transfer_to_fixed_length == 0:
        if array_buffer_is_resizable(abuf):
            # carry over maxByteLength
            max_len = (u64)abuf.max_byte_length
            if new_len > max_len:
                try js_throw_type_error(ctx, "invalid array buffer length")
            # TODO(bnoordhuis) support externally managed RABs
            if is_array_buffer_free(abuf.free_func):
                pmax_len = &max_len

    var res = js_undefined()
    # create an empty AB
    if new_len == 0:
        res = try js_array_buffer_constructor2(ctx, js_undefined(), 0, pmax_len, (u32)ClassId.array_buffer)
        js_detach_array_buffer(ctx, this_val)
    else:
        let old_len = (u64)abuf.byte_length

        # if length mismatch, realloc. Otherwise, use the same backing buffer.
        if new_len != old_len:
            # XXX: we are currently limited to 2 GB
            if new_len > 0x7fffffff:
                try js_throw_range_error(ctx, "invalid array buffer length")

            if not is_array_buffer_free(abuf.free_func):
                # cannot use js_realloc() because the buffer was allocated with a custom
                # allocator
                res = try js_array_buffer_constructor2(ctx, js_undefined(), new_len, pmax_len,
                                                       (u32)ClassId.array_buffer)
                let new_abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, res, (u32)ClassId.array_buffer))
                _ = cutils.memcpy(new_abuf.data, abuf.data,
                                  (usize)cutils.min_int((i32)old_len, (i32)new_len))
                if let free_func = abuf.free_func:
                    free_func(ctx.rt, abuf.opaque, abuf.data)
            else:
                # reallocate the buffer after the new array buffer is created in case the
                # new array buffer creation fails.
                res = try js_array_buffer_constructor2(ctx, js_undefined(), 0, pmax_len,
                                                       (u32)ClassId.array_buffer)
                let new_bs_raw = js_realloc(ctx, abuf.data, (usize)new_len) catch failure:
                    js_free_value(ctx, res)
                    error(failure.code, failure.message)
                let new_bs = (u8*)(new_bs_raw else trap("js_realloc answered none for a nonzero size"))
                if new_len > old_len:
                    _ = cutils.memset(new_bs + (usize)old_len, 0, (usize)(new_len - old_len))
                let new_abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, res, (u32)ClassId.array_buffer))
                js_free(ctx, new_abuf.data)
                new_abuf.data = new_bs
                new_abuf.byte_length = (i32)new_len
        else:
            # can keep the custom free function
            res = try js_array_buffer_constructor3(ctx, js_undefined(), new_len, pmax_len,
                                                   (u32)ClassId.array_buffer,
                                                   abuf.data, abuf.free_func,
                                                   abuf.opaque, false)
        # neuter the backing buffer
        abuf.data = none
        abuf.byte_length = 0
        abuf.detached = 1
        js_array_buffer_update_typed_arrays(abuf)
    return res

# mark: resize and slice ========================================================================

## ArrayBuffer.prototype.resize and SharedArrayBuffer.prototype.grow (`class_id`).
func js_array_buffer_resize(ctx: Context*, this_val: Value, argc: i32, argv: Value*, class_id: i32) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)class_id))
    var len: i64 = 0
    try js_to_int64(ctx, &len, argv[0])
    if abuf.detached != 0:
        try js_throw_type_error_detached_array_buffer(ctx)
    if not array_buffer_is_resizable(abuf):
        try js_throw_type_error(ctx, "array buffer is not resizable")
    # TODO(bnoordhuis) support externally managed RABs
    if not is_array_buffer_free(abuf.free_func):
        try js_throw_type_error(ctx, "external array buffer is not resizable")
    if len < 0 or len > (i64)abuf.max_byte_length:
        try js_throw_range_error(ctx, "invalid array buffer length")
    # SABs can only grow and we don't need to realloc because
    # js_array_buffer_constructor3 commits all memory upfront;
    # regular RABs are resizable both ways and realloc
    if abuf.shared != 0:
        if len < (i64)abuf.byte_length:
            try js_throw_range_error(ctx, "invalid array buffer length")
        # Note this is off-spec; there's supposed to be a single atomic
        # |byteLength| property that's shared across SABs but we store
        # it per SAB instead. That means when thread A calls sab.grow(2)
        # at time t0, and thread B calls sab.grow(1) at time t1, we don't
        # throw a TypeError in thread B as the spec says we should,
        # instead both threads get their own view of the backing memory,
        # 2 bytes big in A, and 1 byte big in B
        abuf.byte_length = (i32)len
    else:
        let data_raw = try js_realloc(ctx, abuf.data, (usize)cutils.max_int((i32)len, 1))
        let data = (u8*)(data_raw else trap("js_realloc answered none for a nonzero size"))
        if len > (i64)abuf.byte_length:
            _ = cutils.memset(data + (usize)abuf.byte_length, 0, (usize)(len - (i64)abuf.byte_length))
        abuf.byte_length = (i32)len
        abuf.data = data
    js_array_buffer_update_typed_arrays(abuf)
    return js_undefined()

## ArrayBuffer.prototype.slice and SharedArrayBuffer.prototype.slice (`class_id`).
func js_array_buffer_slice(ctx: Context*, this_val: Value, argc: i32, argv: Value*, class_id: i32) -> Value!:
    let abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, this_val, (u32)class_id))
    if abuf.detached != 0:
        try js_throw_type_error_detached_array_buffer(ctx)
    let len = (i64)abuf.byte_length

    var start: i64 = 0
    try js_to_int64_clamp(ctx, &start, argv[0], 0, len, len)

    var end = len
    if not js_is_undefined(argv[1]):
        try js_to_int64_clamp(ctx, &end, argv[1], 0, len, len)
    let new_len = cutils.max_int64(end - start, 0)
    let ctor = try js_species_constructor(ctx, this_val, js_undefined())
    var new_obj = js_undefined()
    if js_is_undefined(ctor):
        new_obj = try js_array_buffer_constructor2(ctx, js_undefined(), (u64)new_len, none, (u32)class_id)
    else:
        var args: Value[1] = ---
        args[0] = js_new_int64(new_len)
        new_obj = js_call_constructor(ctx, ctor, 1, &args[0]) catch failure:
            js_free_value(ctx, ctor)
            js_free_value(ctx, args[0])
            error(failure.code, failure.message)
        js_free_value(ctx, ctor)
        js_free_value(ctx, args[0])
    errdefer js_free_value(ctx, new_obj)
    let new_abuf = (ArrayBuffer*)(try js_get_opaque2(ctx, new_obj, (u32)class_id))
    if js_same_value(ctx, new_obj, this_val):
        try js_throw_type_error(ctx, "cannot use identical ArrayBuffer")
    if new_abuf.detached != 0:
        try js_throw_type_error_detached_array_buffer(ctx)
    if (i64)new_abuf.byte_length < new_len:
        try js_throw_type_error(ctx, "new ArrayBuffer is too small")
    # must test again because of side effects
    if abuf.detached != 0 or (i64)abuf.byte_length < start + new_len:
        try js_throw_type_error_detached_array_buffer(ctx)
    _ = cutils.memcpy(new_abuf.data, array_buffer_data_at(abuf.data, (u32)start),
                      (usize)new_len)
    return new_obj

# mark: Tables ==================================================================================

let js_array_buffer_proto_funcs: CFunctionListEntry[9] = [
    CFunctionListEntry(name = "byteLength", prop_flags = 1, def_type = def_cgetset_magic,
                       getter_magic = js_array_buffer_get_byte_length, magic = (i16)ClassId.array_buffer),
    CFunctionListEntry(name = "maxByteLength", prop_flags = 1, def_type = def_cgetset_magic,
                       getter_magic = js_array_buffer_get_max_byte_length, magic = (i16)ClassId.array_buffer),
    CFunctionListEntry(name = "resizable", prop_flags = 1, def_type = def_cgetset_magic,
                       getter_magic = js_array_buffer_get_resizable, magic = (i16)ClassId.array_buffer),
    CFunctionListEntry(name = "detached", prop_flags = 1, def_type = def_cgetset,
                       getter = js_array_buffer_get_detached),
    CFunctionListEntry(name = "resize", def_type = def_cfunc, length = 1, cproto = CFunctionEnum.generic_magic,
                       generic_magic = js_array_buffer_resize, magic = (i16)ClassId.array_buffer),
    CFunctionListEntry(name = "slice", def_type = def_cfunc, length = 2, cproto = CFunctionEnum.generic_magic,
                       generic_magic = js_array_buffer_slice, magic = (i16)ClassId.array_buffer),
    CFunctionListEntry(name = "transfer", def_type = def_cfunc, length = 0, cproto = CFunctionEnum.generic_magic,
                       generic_magic = js_array_buffer_transfer, magic = 0),
    CFunctionListEntry(name = "transferToFixedLength", def_type = def_cfunc, length = 0,
                       cproto = CFunctionEnum.generic_magic, generic_magic = js_array_buffer_transfer, magic = 1),
    CFunctionListEntry(name = "[Symbol.toStringTag]", def_type = def_prop_string,
                       prop_flags = (u8)prop_configurable, string_value = "ArrayBuffer"),
]

# SharedArrayBuffer

let js_shared_array_buffer_funcs: CFunctionListEntry[1] = [
    CFunctionListEntry(name = "[Symbol.species]", prop_flags = 1, def_type = def_cgetset, getter = js_get_this),
]

let js_shared_array_buffer_proto_funcs: CFunctionListEntry[6] = [
    CFunctionListEntry(name = "byteLength", prop_flags = 1, def_type = def_cgetset_magic,
                       getter_magic = js_array_buffer_get_byte_length, magic = (i16)ClassId.shared_array_buffer),
    CFunctionListEntry(name = "maxByteLength", prop_flags = 1, def_type = def_cgetset_magic,
                       getter_magic = js_array_buffer_get_max_byte_length,
                       magic = (i16)ClassId.shared_array_buffer),
    CFunctionListEntry(name = "growable", prop_flags = 1, def_type = def_cgetset_magic,
                       getter_magic = js_array_buffer_get_resizable, magic = (i16)ClassId.shared_array_buffer),
    CFunctionListEntry(name = "grow", def_type = def_cfunc, length = 1, cproto = CFunctionEnum.generic_magic,
                       generic_magic = js_array_buffer_resize, magic = (i16)ClassId.shared_array_buffer),
    CFunctionListEntry(name = "slice", def_type = def_cfunc, length = 2, cproto = CFunctionEnum.generic_magic,
                       generic_magic = js_array_buffer_slice, magic = (i16)ClassId.shared_array_buffer),
    CFunctionListEntry(name = "[Symbol.toStringTag]", def_type = def_prop_string,
                       prop_flags = (u8)prop_configurable, string_value = "SharedArrayBuffer"),
]