]> git.argeo.org Git - lgpl/argeo-commons.git/blob - jni/org_argeo_api_uuid_libuuid/org_argeo_api_uuid_libuuid_LibuuidFactory.c
Prepare release
[lgpl/argeo-commons.git] / jni / org_argeo_api_uuid_libuuid / org_argeo_api_uuid_libuuid_LibuuidFactory.c
1 #include <jni.h>
2 #include <uuid.h>
3 #include "org_argeo_api_uuid_libuuid_LibuuidFactory.h"
4
5 /*
6 * UTILITIES
7 */
8
9 static inline jobject fromBytes(JNIEnv *env, uuid_t out) {
10 jlong msb = 0;
11 jlong lsb = 0;
12
13 for (int i = 0; i < 8; i++)
14 msb = (msb << 8) | (out[i] & 0xff);
15 for (int i = 8; i < 16; i++)
16 lsb = (lsb << 8) | (out[i] & 0xff);
17
18 jclass uuidClass = (*env)->FindClass(env, "java/util/UUID");
19 jmethodID uuidConstructor = (*env)->GetMethodID(env, uuidClass, "<init>",
20 "(JJ)V");
21
22 jobject jUUID = (*env)->AllocObject(env, uuidClass);
23 (*env)->CallVoidMethod(env, jUUID, uuidConstructor, msb, lsb);
24
25 return jUUID;
26 }
27
28 static inline void toBytes(JNIEnv *env, jobject jUUID, uuid_t result) {
29
30 jclass uuidClass = (*env)->FindClass(env, "java/util/UUID");
31 jmethodID getMostSignificantBits = (*env)->GetMethodID(env, uuidClass,
32 "getMostSignificantBits", "()J");
33 jmethodID getLeastSignificantBits = (*env)->GetMethodID(env, uuidClass,
34 "getLeastSignificantBits", "()J");
35
36 jlong msb = (*env)->CallLongMethod(env, jUUID, getMostSignificantBits);
37 jlong lsb = (*env)->CallLongMethod(env, jUUID, getLeastSignificantBits);
38
39 for (int i = 0; i < 8; i++)
40 result[i] = (unsigned char) ((msb >> ((7 - i) * 8)) & 0xff);
41 for (int i = 8; i < 16; i++)
42 result[i] = (unsigned char) ((lsb >> ((15 - i) * 8)) & 0xff);
43 }
44
45 /*
46 * JNI IMPLEMENTATION
47 */
48
49 JNIEXPORT jobject JNICALL Java_org_argeo_api_uuid_libuuid_LibuuidFactory_timeUUID(
50 JNIEnv *env, jobject uuidFactory) {
51 uuid_t out;
52
53 uuid_generate_time(out);
54 return fromBytes(env, out);
55 }
56
57 JNIEXPORT jobject JNICALL Java_org_argeo_api_uuid_libuuid_LibuuidFactory_nameUUIDv5(
58 JNIEnv *env, jobject uuidFactory, jobject namespaceUuid,
59 jbyteArray name) {
60 uuid_t ns;
61 uuid_t out;
62
63 toBytes(env, namespaceUuid, ns);
64 jsize length = (*env)->GetArrayLength(env, name);
65 jbyte *bytes = (*env)->GetByteArrayElements(env, name, 0);
66
67 uuid_generate_sha1(out, ns, bytes, length);
68 return fromBytes(env, out);
69 }
70
71 JNIEXPORT jobject JNICALL Java_org_argeo_api_uuid_libuuid_LibuuidFactory_nameUUIDv3(
72 JNIEnv *env, jobject uuidFactory, jobject namespaceUuid,
73 jbyteArray name) {
74 uuid_t ns;
75 uuid_t out;
76
77 toBytes(env, namespaceUuid, ns);
78 jsize length = (*env)->GetArrayLength(env, name);
79 jbyte *bytes = (*env)->GetByteArrayElements(env, name, 0);
80
81 uuid_generate_md5(out, ns, bytes, length);
82 return fromBytes(env, out);
83 }
84
85 JNIEXPORT jobject JNICALL Java_org_argeo_api_uuid_libuuid_LibuuidFactory_randomUUIDStrong(
86 JNIEnv *env, jobject uuidFactory) {
87 uuid_t out;
88
89 uuid_generate_random(out);
90 return fromBytes(env, out);
91 }