napi_value aws_napi_hash_md5_compute()

in source/crypto.c [167:222]


napi_value aws_napi_hash_md5_compute(napi_env env, napi_callback_info info) {

    napi_value node_args[2];
    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 retreive callback information");
        return NULL;
    }
    if (num_args != AWS_ARRAY_SIZE(node_args)) {
        napi_throw_error(env, NULL, "hash_md5_compute needs exactly 2 arguments");
        return NULL;
    }

    struct aws_byte_buf to_hash;
    if (aws_byte_buf_init_from_napi(&to_hash, env, node_args[0])) {
        napi_throw_type_error(env, NULL, "to_hash argument must be a string or array");
        return NULL;
    }

    size_t digest_size = AWS_MD5_LEN;
    if (!aws_napi_is_null_or_undefined(env, node_args[1])) {

        uint32_t truncate_to = 0;
        if (napi_get_value_uint32(env, node_args[1], &truncate_to)) {
            napi_throw_type_error(env, NULL, "truncate_to argument must be undefined or a positive number");
            return NULL;
        }

        if (digest_size > truncate_to) {
            digest_size = truncate_to;
        }
    }

    napi_value arraybuffer;
    void *data = NULL;
    if (napi_create_arraybuffer(env, digest_size, &data, &arraybuffer)) {
        napi_throw_error(env, NULL, "Failed to create output arraybuffer");
        return NULL;
    }

    struct aws_byte_cursor to_hash_cur = aws_byte_cursor_from_buf(&to_hash);
    struct aws_byte_buf out_buf = aws_byte_buf_from_empty_array(data, digest_size);
    if (aws_md5_compute(aws_napi_get_allocator(), &to_hash_cur, &out_buf, digest_size)) {
        aws_napi_throw_last_error(env);
    }

    napi_value dataview;
    if (napi_create_dataview(env, digest_size, arraybuffer, 0, &dataview)) {
        napi_throw_error(env, NULL, "Failed to create output dataview");
        return NULL;
    }

    aws_byte_buf_clean_up(&to_hash);

    return dataview;
}