1 // Copyright 2020 The Pigweed Authors
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
7 // https://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
15 // This file provides a Java Native Interface (JNI) version of the Detokenizer
16 // class. This facilitates using the tokenizer library from Java or other JVM
17 // languages. A corresponding Java class is provided in Detokenizer.java.
24 #include "pw_preprocessor/concat.h"
25 #include "pw_tokenizer/detokenize.h"
26 #include "pw_tokenizer/token_database.h"
28 #define DETOKENIZER_METHOD(method) \
29 JNICALL PW_CONCAT(Java_dev_pigweed_tokenizer_, Detokenizer_, method)
31 namespace pw::tokenizer {
34 Detokenizer* HandleToPointer(jlong handle) {
35 Detokenizer* detokenizer = nullptr;
36 std::memcpy(&detokenizer, &handle, sizeof(detokenizer));
37 static_assert(sizeof(detokenizer) <= sizeof(handle));
41 jlong PointerToHandle(Detokenizer* detokenizer) {
43 std::memcpy(&handle, &detokenizer, sizeof(detokenizer));
44 static_assert(sizeof(handle) >= sizeof(detokenizer));
52 static_assert(sizeof(jbyte) == 1u);
54 JNIEXPORT jlong DETOKENIZER_METHOD(newNativeDetokenizer)(JNIEnv* env,
57 jbyte* const data = env->GetByteArrayElements(array, nullptr);
58 const jsize size = env->GetArrayLength(array);
60 TokenDatabase tokens = TokenDatabase::Create(std::span(data, size));
62 PointerToHandle(new Detokenizer(tokens.ok() ? tokens : TokenDatabase()));
64 env->ReleaseByteArrayElements(array, data, 0);
68 JNIEXPORT void DETOKENIZER_METHOD(deleteNativeDetokenizer)(JNIEnv*,
71 delete HandleToPointer(handle);
74 JNIEXPORT jstring DETOKENIZER_METHOD(detokenizeNative)(JNIEnv* env,
78 jbyte* const data = env->GetByteArrayElements(array, nullptr);
79 const jsize size = env->GetArrayLength(array);
81 DetokenizedString result = HandleToPointer(handle)->Detokenize(data, size);
83 env->ReleaseByteArrayElements(array, data, 0);
85 return result.matches().empty()
87 : env->NewStringUTF(result.BestString().c_str());
92 } // namespace pw::tokenizer