1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include <memory>
18
19 #include <binder/Parcel.h>
20
21 #include "LowpanChannelInfoTest.h"
22
23 using android::net::lowpan::LowpanChannelInfo;
24
25 /**
26 * Reads exactly one LowpanChannelInfo from 'parcelData' assuming that it is a Parcel. Any bytes afterward
27 * are ignored.
28 */
unmarshall(JNIEnv * env,jbyteArray parcelData)29 static LowpanChannelInfo unmarshall(JNIEnv* env, jbyteArray parcelData) {
30 const int length = env->GetArrayLength(parcelData);
31
32 std::unique_ptr<uint8_t> bytes(new uint8_t[length]);
33 env->GetByteArrayRegion(parcelData, 0, length, reinterpret_cast<jbyte*>(bytes.get()));
34
35 android::Parcel p;
36 p.setData(bytes.get(), length);
37
38 LowpanChannelInfo value;
39 value.readFromParcel(&p);
40 return value;
41 }
42
43 /**
44 * Creates a Java byte[] array and writes the contents of 'addr' to it as a Parcel containing
45 * exactly one object.
46 *
47 * Every LowpanChannelInfo maps to a unique parcel object, so both 'marshall(e, unmarshall(e, x))' and
48 * 'unmarshall(e, marshall(e, x))' should be fixed points.
49 */
marshall(JNIEnv * env,const LowpanChannelInfo & addr)50 static jbyteArray marshall(JNIEnv* env, const LowpanChannelInfo& addr) {
51 android::Parcel p;
52 addr.writeToParcel(&p);
53 const int length = p.dataSize();
54
55 jbyteArray parcelData = env->NewByteArray(length);
56 env->SetByteArrayRegion(parcelData, 0, length, reinterpret_cast<const jbyte*>(p.data()));
57
58 return parcelData;
59 }
60
61 extern "C"
Java_android_net_lowpan_LowpanChannelInfoTest_readAndWriteNative(JNIEnv * env,jclass,jbyteArray inParcel)62 JNIEXPORT jbyteArray Java_android_net_lowpan_LowpanChannelInfoTest_readAndWriteNative(JNIEnv* env, jclass,
63 jbyteArray inParcel) {
64 const LowpanChannelInfo value = unmarshall(env, inParcel);
65 return marshall(env, value);
66 }
67