napi_value aws_napi_io_input_stream_new()

in source/io.c [722:774]


napi_value aws_napi_io_input_stream_new(napi_env env, napi_callback_info info) {
    napi_value node_args[1];
    size_t num_args = AWS_ARRAY_SIZE(node_args);
    if (napi_get_cb_info(env, info, &num_args, node_args, NULL, NULL)) {
        napi_throw_error(env, NULL, "Failed to retrieve callback information");
        return NULL;
    }
    if (num_args != AWS_ARRAY_SIZE(node_args)) {
        napi_throw_error(env, NULL, "io_input_stream_new requires exactly 1 arguments");
        return NULL;
    }

    int64_t capacity = 0;
    if (napi_get_value_int64(env, node_args[0], &capacity)) {
        napi_throw_error(env, NULL, "capacity must be a number");
        return NULL;
    }

    struct aws_allocator *allocator = aws_napi_get_allocator();
    struct aws_napi_input_stream_impl *impl = aws_mem_calloc(allocator, 1, sizeof(struct aws_napi_input_stream_impl));
    if (!impl) {
        napi_throw_error(env, NULL, "Unable to allocate native aws_input_stream");
        return NULL;
    }

    impl->base.allocator = allocator;
    impl->base.impl = impl;
    impl->base.vtable = &s_input_stream_vtable;
    if (aws_mutex_init(&impl->mutex)) {
        aws_napi_throw_last_error(env);
        goto failed;
    }

    if (aws_byte_buf_init(&impl->buffer, allocator, 16 * 1024)) {
        napi_throw_error(env, NULL, "Unable to allocate stream buffer");
        goto failed;
    }

    napi_value node_external = NULL;
    if (napi_create_external(env, impl, NULL, NULL, &node_external)) {
        napi_throw_error(env, NULL, "Unable to create external for native aws_input_stream");
        goto failed;
    }

    return node_external;

failed:
    if (impl) {
        s_input_stream_destroy(&impl->base);
    }

    return NULL;
}