#include <stdlib.h>
#include "mpz_jni.h"

static const size_t JBYTE_BIT = sizeof(jbyte) * CHAR_BIT;

void mpz_init_set_jbyteArray(mpz_t value, JNIEnv *env, jbyteArray array)
{
    size_t length = (size_t)(*env)->GetArrayLength(env, array);
    jbyte *bytes = (*env)->GetByteArrayElements(env, array, NULL);

    mpz_init2(value, JBYTE_BIT * length);
    mpz_import(value, length, 1, sizeof(jbyte), 1, 0, (void*)bytes);

    (*env)->ReleaseByteArrayElements(env, array, bytes, 0);
}

jbyteArray mpz_get_jbyteArray(JNIEnv *env, mpz_t value)
{
    jint length = (jint)mpz_sizeinbase(value, 1 << JBYTE_BIT) + 1;
    jbyteArray array = (*env)->NewByteArray(env, length);
    jbyte *bytes = (*env)->GetByteArrayElements(env, array, NULL);

    bytes[0] = 0x00;
    mpz_export((void*)&bytes[1], NULL, 1, sizeof(jbyte), 1, 0, value);

    (*env)->ReleaseByteArrayElements(env, array, bytes, 0);

    return array;
}
