1 /*
2  * Copyright (C) 2010 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 #ifndef LIBNATIVEHELPER_HEADER_ONLY_INCLUDE_NATIVEHELPER_SCOPED_BYTES_H_
18 #define LIBNATIVEHELPER_HEADER_ONLY_INCLUDE_NATIVEHELPER_SCOPED_BYTES_H_
19 
20 #include "jni.h"
21 #include "nativehelper_utils.h"
22 
23 /**
24  * ScopedBytesRO and ScopedBytesRW attempt to paper over the differences between byte[]s and
25  * ByteBuffers. This in turn helps paper over the differences between non-direct ByteBuffers backed
26  * by byte[]s, direct ByteBuffers backed by bytes[]s, and direct ByteBuffers not backed by byte[]s.
27  * (On Android, this last group only contains MappedByteBuffers.)
28  */
29 template<bool readOnly>
30 class ScopedBytes {
31 public:
32     ScopedBytes(JNIEnv* env, jobject object)
33     : mEnv(env), mObject(object), mByteArray(NULL), mPtr(NULL)
34     {
35         if (mObject == NULL) {
36             jniThrowNullPointerException(mEnv);
37         } else {
38             jclass byteArrayClass = env->FindClass("[B");
39             if (mEnv->IsInstanceOf(mObject, byteArrayClass)) {
40                 mByteArray = reinterpret_cast<jbyteArray>(mObject);
41                 mPtr = mEnv->GetByteArrayElements(mByteArray, NULL);
42             } else {
43                 mPtr = reinterpret_cast<jbyte*>(mEnv->GetDirectBufferAddress(mObject));
44             }
45             mEnv->DeleteLocalRef(byteArrayClass);
46         }
47     }
48 
49     ~ScopedBytes() {
50         if (mByteArray != NULL) {
51             mEnv->ReleaseByteArrayElements(mByteArray, mPtr, readOnly ? JNI_ABORT : 0);
52         }
53     }
54 
55 private:
56     JNIEnv* const mEnv;
57     const jobject mObject;
58     jbyteArray mByteArray;
59 
60 protected:
61     jbyte* mPtr;
62 
63 private:
64     DISALLOW_COPY_AND_ASSIGN(ScopedBytes);
65 };
66 
67 class ScopedBytesRO : public ScopedBytes<true> {
68 public:
69     ScopedBytesRO(JNIEnv* env, jobject object) : ScopedBytes<true>(env, object) {}
70     const jbyte* get() const {
71         return mPtr;
72     }
73 };
74 
75 class ScopedBytesRW : public ScopedBytes<false> {
76 public:
77     ScopedBytesRW(JNIEnv* env, jobject object) : ScopedBytes<false>(env, object) {}
78     jbyte* get() {
79         return mPtr;
80     }
81 };
82 
83 #endif  // LIBNATIVEHELPER_HEADER_ONLY_INCLUDE_NATIVEHELPER_SCOPED_BYTES_H_
84